Find First and Last Position of Element in Sorted Array

Medium

Topics
ArrayBinary Search

Given a sorted array nums and a target, return [first, last] — the first and last index of target. Return [-1, -1] if it is not found. Must run in O(log n).

Example 1

5071728384105
The target occupies a block, and the answer is its two ends, [3, 4].
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2

5071728384105
Target 6 is absent, so the answer is [-1, -1].
Input:  nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Constraints

  • 0 <= nums.length <= 10^5
  • nums is sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A linear scan finds both ends in O(n), which the sortedness makes unnecessary. The problem explicitly asks for O(log n), so binary search it is — but a single binary search finds some occurrence, not the first or last one, because it stops as soon as it hits the target.

The fix is to keep going. On a match, record the index and then continue searching the side you care about: for the first occurrence, keep moving the upper bound left; for the last, keep moving the lower bound right. Each search still halves the range every step, so each is O(log n) and the pair costs two of them.

That is what the low flag selects: the same routine, with the post-match direction flipped.

Approach

  1. Binary search recording the last index where the target was seen.
  2. On a match, narrow toward the left for the first position, toward the right for the last.
  3. Run it twice and return both; [-1, -1] if never found.

Dry Run

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

first occurrence (narrow left on a match):
  lo=0 hi=5  mid=2  nums[2]=7 < 8   -> lo=3
  lo=3 hi=5  mid=4  nums[4]=8 match, record 4, hi=3
  lo=3 hi=3  mid=3  nums[3]=8 match, record 3, hi=2
  lo > hi    -> first = 3

last occurrence (narrow right on a match):
  lo=0 hi=5  mid=2  7 < 8  -> lo=3
  lo=3 hi=5  mid=4  match, record 4, lo=5
  lo=5 hi=5  mid=5  nums[5]=10 > 8 -> hi=4
  lo > hi    -> last = 4

answer [3,4]

Notice the first search records 4 before finding 3 — the recorded value is overwritten as the search pushes further left, which is why recording rather than returning is the key move.

Complexity

  • Time — O(log n): two binary searches, each halving the range.
  • Space — O(1): indices only.

Common Pitfalls

  • Returning on the first match. That gives an arbitrary occurrence, which is neither bound.
  • Finding one end and then scanning linearly for the other. It passes the tests and is O(n) on a run of equal values, which defeats the point.
  • Flipping the narrowing direction, so the "first" search drifts right.
  • Forgetting the not-found case. The recorded value stays at its initial -1, which is exactly the required answer.
  • Using (lo + hi) / 2 in a language where lo + hi can overflow. Safe at these sizes, but lo + (hi - lo) / 2 is the habit.

Full Solution — all languages

class Solution:
    def searchRange(self, nums, target):
        def bound(low):
            lo, hi, res = 0, len(nums) - 1, -1
            while lo <= hi:
                mid = (lo + hi) // 2
                if nums[mid] == target:
                    res = mid
                    if low:
                        hi = mid - 1
                    else:
                        lo = mid + 1
                elif nums[mid] < target:
                    lo = mid + 1
                else:
                    hi = mid - 1
            return res
        return [bound(True), bound(False)]
SensAI
Beta
Tap the mic to stop voice mode