Skip to content
RED SAGSkills
medium30 ptsbinary-search

First and Last Occurrence

An index stores timestamps nums sorted in non-decreasing order, possibly with repeats. Return [first, last], the first and last positions of target, or [-1, -1] if it is absent.

Your solution must run in O(log n).

Example 1

Input: nums = [1, 3, 3, 3, 7, 9], target = 3
Output: [1, 3]

Example 2

Input: nums = [2, 4, 6], target = 5
Output: [-1, -1]

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i], target <= 10^9
Hint 1

Write one binary search that finds the first index with value >= x.

Hint 2

Use it for target and for target + 1.

Good practice for: Backend Developer, Full Stack Developer, Data Engineer, Database Administrator, Site Reliability Engineer, Cloud Engineer

Run checks your code on 2 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.