Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Binary search for first/last occurrence runs on the sorted array [5, 6, 7, 7, 15, 18, 19, 20] for target 7. What (first index, last index) pair (0-based) does it return?

  1. A. (2, 3)
  2. B. (2, 2)
  3. C. (1, 3)
  4. D. (2, 4)

Correct answer: A. (2, 3)

The first-occurrence search keeps moving left after a match (hi = mid − 1) to find the earliest index, and the last-occurrence search keeps moving right (lo = mid + 1) to find the latest; for 7 in this array that gives first index 2 and last index 3.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic