First and Last Index

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write searchRange(sorted, target): sorted is an array of numbers in ascending order, and numbers may repeat. Return [first, last], the first and last index where target appears, or [-1, -1] if it doesn't. Don't change sorted. For example, searchRange([5, 7, 7, 8, 8, 10], 8) is [3, 4], and searchRange([5, 7, 7, 8, 8, 10], 6) is [-1, -1]. The checks run 100,000 searches on arrays of up to a million numbers, one with a number repeated almost a million times, so scanning, indexOf, or stepping out from one match is too slow.

Your code must pass

  • Finds the first and last index of a repeated number
  • Works when the number appears once
  • Returns [-1, -1] for missing numbers
  • Is fast enough for 100,000 searches