Data Structures & AlgorithmsVery hardProduct-company MCQ pattern

Binary search for first/last occurrence runs on the sorted array [2, 7, 9, 11, 16, 16, 17, 18] for target 16. What (first index, last index) pair (0-based) does it return?

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

Correct answer: B. (4, 5)

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 16 in this array that gives first index 4 and last index 5.

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

Exams that ask this topic