First and Last Place of a Value

EasyBinary Search≈ 20 min

You are given a list of integers nums, sorted from smallest to largest, in which values may repeat, and a target. Return [first, last]: the index of the first copy of target and the index of its last copy. If target is not in the list, return [-1, -1].

Examples

text
nums = [1, 3, 3, 3, 5, 8], target = 3   →  [1, 3]
nums = [1, 3, 3, 3, 5, 8], target = 4   →  [-1, -1]
nums = [2, 2], target = 2               →  [0, 1]
nums = [7], target = 7                  →  [0, 0]

Constraints

  • Between 0 and 100,000 numbers, sorted, each between -1,000,000,000 and 1,000,000,000.
  • Aim for O(log n), even when the target fills most of the list: a list four times longer should take only a couple of steps more.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.