Skip to main content

34 - Find First and Last Position of Element in Sorted Array

Difficulty: Medium | Pattern: Binary Search (Left & Right Bounds) | Company tags: Facebook, Amazon, Google, LinkedIn

Problem Statement

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Approach: Two Binary Searches — O(log n)

Run binary search twice: once to find the leftmost occurrence, once for the rightmost.

def searchRange(nums: list[int], target: int) -> list[int]:
def find_left():
left, right = 0, len(nums) - 1
idx = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
idx = mid
right = mid - 1 # keep searching left
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return idx

def find_right():
left, right = 0, len(nums) - 1
idx = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
idx = mid
left = mid + 1 # keep searching right
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return idx

return [find_left(), find_right()]

Using bisect Module

import bisect

def searchRange(nums: list[int], target: int) -> list[int]:
left = bisect.bisect_left(nums, target)
if left == len(nums) or nums[left] != target:
return [-1, -1]
right = bisect.bisect_right(nums, target) - 1
return [left, right]

Dry Run

nums = [5,7,7,8,8,10], target = 8

Left search:

  • left=0, right=5, mid=2: nums[2]=7 lt 8 → left=3
  • left=3, right=5, mid=4: nums[4]=8 → idx=4, right=3
  • left=3, right=3, mid=3: nums[3]=8 → idx=3, right=2
  • left=3, right=2: stop → return 3

Right search:

  • left=0, right=5, mid=2: nums[2]=7 lt 8 → left=3
  • left=3, right=5, mid=4: nums[4]=8 → idx=4, left=5
  • left=5, right=5, mid=5: nums[5]=10 gt 8 → right=4
  • left=5, right=4: stop → return 4

[3, 4]

Complexity

  • Time: O(log n) — two binary searches
  • Space: O(1)