Data Structures & AlgorithmsHardProduct-company MCQ pattern

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

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

Correct answer: D. (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 19 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