Skip to content

Find First and Last Position of Element in Sorted Array

Find where a value's run of copies starts and ends in a sorted array, with two lower bound searches.

MediumBinary Search
Solve on LeetCode

The problem

You get an integer array nums sorted in non-decreasing order, which may contain repeated values, and an integer target. Return [first, last], the first and last index where target appears, or [-1, -1] if it does not appear. Your solution must run in O(log n) time.

Input nums = [1, 4, 4, 4, 6, 9], target = 4

Output [1, 3]

The 4s fill indices 1 to 3.

Input nums = [2, 2, 3], target = 5

Output [-1, -1]

5 is not in the array.

Key constraint: O(log n) time, so finding one copy and walking outward is not enough: the run of copies can be as long as the whole array.

How to spot the pattern

  • The array is sorted and you need the boundaries of a value, not just any copy of it.
  • O(log n) is required even when the value repeats many times.

The idea

Write one binary search, lowerBound(x), that finds the first index whose value is at least x. The first copy of target sits at lowerBound(target), and the last copy sits just before lowerBound(target + 1), where the bigger values begin. If the first position is past the end or doesn't hold target, the value is missing.

Brute force: Scan the whole array for the first and last copy, which takes O(n) time.

Step by step

  1. 1Write lowerBound(x): with lo = 0 and hi = n, while lo < hi, set lo = mid + 1 if nums[mid] < x, else set hi = mid; return lo.
  2. 2Compute first = lowerBound(target).
  3. 3If first == n or nums[first] != target, return [-1, -1].
  4. 4Otherwise compute last = lowerBound(target + 1) - 1 and return [first, last].

See the pattern move

The binary search pattern on a small example. Step through it, or press play.

Code

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def lower_bound(x: int) -> int:
            # first index whose value is at least x, or len(nums) if there is none
            lo, hi = 0, len(nums)
            while lo < hi:
                mid = lo + (hi - lo) // 2
                if nums[mid] < x:
                    lo = mid + 1
                else:
                    hi = mid
            return lo

        first = lower_bound(target)
        if first == len(nums) or nums[first] != target:
            return [-1, -1]
        last = lower_bound(target + 1) - 1
        return [first, last]

Complexity

Time

O(log n)

Space

O(1)

Two binary searches of O(log n) each, however many copies of the target there are.

Watch out for

  • Finding any copy with a plain binary search and then walking left and right, which is O(n) when most of the array is the target.
  • Reading nums[first] without first checking first < n, which runs past the end when the target is bigger than everything.
  • Mixing loop styles: with hi = n and while lo < hi, the update must be hi = mid, not hi = mid - 1.

Follow-up questions

Can you find the last copy without searching for target + 1?

Write an upper bound search that also moves right on equal values: if nums[mid] <= target, set lo = mid + 1. The last copy is the upper bound minus 1, and it avoids overflow when the target is the largest int.

How would you count how many times the target appears?

It is last - first + 1, or the upper bound minus the lower bound, still in O(log n).

In Hinglish

Ek lowerBound function likho: pehla index jahan value >= x ho. First = lowerBound(target), aur last = lowerBound(target + 1) - 1.

Related problems