CodingNodes / Binary Search / Find First and Last Position of Element in Sorted Array System design Space play · ←→ step · R restart

Problem

You get an array nums sorted in non-decreasing order, so equal values may repeat, and a number target.

Return the first and last index where target appears, as [first, last]. If it never appears, return [-1, -1]. Your solution has to run in O(log n) time.

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • −10⁹ ≤ nums[i], target ≤ 10⁹
  • nums is sorted in non-decreasing order

Examples: pick one to animate

Solutions

TimeO(log n) SpaceO(1)

Time: Two binary searches, each halving its range every step, so about 2 · log2(n) probes in total.

Space: Only lo, hi, mid, first and last are stored.

A lower-bound search finds the first index whose value is not less than x. Run it for target to get the first position, and for target + 1 to get one past the last position. Check that the first position really holds the target before trusting it.