Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

First and last position of a value

Medium · Target 15 minutes · Binary search · Type asked atMetaGoogleLinkedIn

Given an array nums sorted in non-decreasing order, which may contain repeated values, and an integer target, return [first, last]: the first and last index at which target appears. If it does not appear, return [−1, −1]. Use O(log n) comparisons.

Examples

InputOutputWhy
nums = [5, 7, 7, 8, 8, 10], target = 8[3, 4]
nums = [5, 7, 7, 8, 8, 10], target = 6[-1, -1]
nums = [], target = 0[-1, -1]

Constraints

  • 0 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i], target ≤ 10⁹
  • nums is non-decreasing

Hints

Hint 1

Finding target and then walking left and right is O(n) when the whole array is one value.

Hint 2

The first occurrence is the first index with nums[i] ≥ target. Check that it holds target.

Hint 3

The last occurrence is one before the first index with nums[i] > target.

Where people lose marks

  • Stopping the first search as soon as nums[mid] == target: that finds an occurrence, not the first one.
  • Reading nums[first] when first = n.
  • Forgetting the empty array, where both searches return 0 and nums[0] does not exist.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.