InterviewPrepKit

Home / Coding / Binary Search

Find First and Last Position of Element in Sorted Array

medium Original β†—
Solving tips
  • Duplicates turn 'find the target' into 'find the boundaries': run two boundary binary searches instead of stopping on the first match.
  • Find the lower bound (first index with nums[i] >= target) and upper bound (first index with nums[i] > target); the answer is [lower, upper-1], or [-1,-1] when lower == upper.
  • A plain search then expanding outward is O(n) worst case (e.g. all-equal array), which fails the O(log n) requirement, so keep the search shrinking on equality.
  • Both searches are O(log n), O(1) space; equivalently use bisect_left and bisect_right. Watch the empty-array and absent-target cases.

Problem

You are given an integer array nums sorted in non-decreasing order (duplicates allowed) and a value target. Return a two-element list [first, last] where first is the index of the first occurrence of target and last is the index of its last occurrence. If target does not appear in nums, return [-1, -1].

The required time complexity is O(log n).

Examples

  • Input: nums = [5, 7, 7, 8, 8, 10], target = 8 β†’ Output: [3, 4] (8 appears at indices 3 and 4.)
  • Input: nums = [5, 7, 7, 8, 8, 10], target = 6 β†’ Output: [-1, -1] (6 is absent.)
  • Input: nums = [2, 2, 2, 2], target = 2 β†’ Output: [0, 3] (The whole array is the target; the range spans everything.)

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i], target <= 10^9
  • nums is sorted in non-decreasing order (may contain duplicates, may be empty).
  • Required time complexity: O(log n).

Think about it first

Hint 1 A plain binary search lands on *some* occurrence of the target. Why is scanning outward from there to find the edges not O(log n)? (Think of an array that is all 8s.)
Hint 2 "First occurrence" and "last occurrence" are two separate boundary questions. Can you design a binary search that, on finding the target, keeps going *left* anyway? And a mirror one that keeps going right?
Hint 3 Run two boundary binary searches: the first index with `nums[i] >= target` (lower bound) and the first index with `nums[i] > target` (upper bound). If they're equal, the target is absent; otherwise the answer is `[lower, upper - 1]`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.