Find First and Last Position of Element in Sorted Array (LeetCode 34): Solution and Explanation

Medium
Array
Binary Search

Given an array sorted in non-decreasing order and a target value, return the index of the target's first occurrence and its last occurrence. If the target does not appear, return [-1, -1]. The solution is expected to run in O(log n) time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The simple approach walks the array once, recording the first index that equals the target and the last one. That is O(n), which misses the logarithmic requirement. A tempting middle ground is to binary search for any copy of the target and then walk left and right to find the ends, but if the array is mostly the target, that walk is O(n) again.

The better idea is to recognize that you are searching for two boundaries, not one value. The first occurrence is the leftmost index where nums[i] >= target holds and the value equals the target. The last occurrence is the rightmost index where nums[i] <= target holds and the value equals the target. Each of those is a classic binary search on a monotone condition.

The only change from ordinary binary search is what happens when you find a match. Instead of returning immediately, you remember the index as a candidate and keep searching in the direction of the boundary you want: left for the first occurrence, right for the last. The search continues to halve the range, so each one finishes in O(log n), and the last candidate you recorded is the true boundary.

Approach: Two boundary binary searches

  1. Write findFirst with left = 0, right = len(nums) - 1 and result = -1.
  2. In findFirst, compute mid. If nums[mid] >= target, record mid when it equals the target, then set right = mid - 1 to keep looking left. Otherwise set left = mid + 1.
  3. Write findLast the same way, but branch on nums[mid] <= target. Record a match and move left = mid + 1 to keep looking right; otherwise set right = mid - 1.
  4. Both loops run while left <= right and return the last recorded candidate, or -1 if none matched.
  5. Return [findFirst(), findLast()].

Step-by-step example

nums = [5,7,7,8,8,10], target = 8
  1. findFirst starts with left = 0 and right = 5. mid = 2 holds 7, which is less than 8, so left becomes 3.
  2. mid = 4 holds 8. It is a match, so result = 4, and right becomes 3 to look further left.
  3. mid = 3 holds 8 again, so result = 3 and right becomes 2. The loop ends and the first position is 3.
  4. findLast starts the same way. mid = 2 holds 7, which is at most 8, so left becomes 3. mid = 4 holds 8, so result = 4 and left becomes 5.
  5. mid = 5 holds 10, which is greater, so right becomes 4. The loop ends and the answer is [3, 4].

Code: Python, Java, C++

1class Solution:
2    def searchRange(self, nums: List[int], target: int) -> List[int]:
3        def findFirst():
4            left, right = 0, len(nums) - 1
5            result = -1
6            while left <= right:
7                mid = (left + right) // 2
8                if nums[mid] >= target:
9                    if nums[mid] == target:
10                        result = mid
11                    right = mid - 1
12                else:
13                    left = mid + 1
14            return result
15
16        def findLast():
17            left, right = 0, len(nums) - 1
18            result = -1
19            while left <= right:
20                mid = (left + right) // 2
21                if nums[mid] <= target:
22                    if nums[mid] == target:
23                        result = mid
24                    left = mid + 1
25                else:
26                    right = mid - 1
27            return result
28
29        return [findFirst(), findLast()]

Time and space complexity

Time

O(log n)

Each of the two searches halves its range on every iteration, so together they take about 2 log n steps.

Space

O(1)

Only a few index variables are used in each helper.

Other approaches

Lower bound twice (time O(log n), space O(1))

Use one lower-bound search that returns the first index with nums[i] >= x. The first position is lower_bound(target), and the last is lower_bound(target + 1) - 1, after checking that the target exists. In Python, bisect_left and bisect_right do exactly this.

Linear scan (time O(n), space O(1))

Walk the array once and record the first and last indices that match. It is trivial to write and fine for small inputs, but it does not meet the logarithmic requirement.

Common mistakes

  • Returning as soon as nums[mid] == target. That finds some occurrence, not necessarily the first or last one.
  • Expanding outward linearly from a found match. On an array full of the target value this degrades to O(n).
  • Using left < right with right = mid - 1, which can skip the final candidate. Pair left <= right with the mid - 1 and mid + 1 updates consistently.
  • Forgetting the empty array. With right = -1 the loops do not run and both helpers return -1, which is correct, but code that reads nums[0] first will crash.

Frequently asked questions

Why not just use one binary search and scan outward?

If the target repeats many times, the outward scan touches every copy, making the worst case O(n). Two boundary searches keep the guarantee at O(log n) regardless of how many duplicates exist.

Can this be done with a single binary search?

Not cleanly. The two boundaries are independent, so you need two searches, but each is O(log n), and two logarithmic searches are still O(log n) overall.

How does bisect relate to this problem?

bisect_left(nums, target) returns the first index where the target could be inserted, which is the first occurrence if it exists, and bisect_right(nums, target) - 1 is the last occurrence. The custom helpers here implement the same logic by hand.

What if the target is not in the array?

Neither helper ever records a match, so both return -1 and the answer is [-1, -1].