Data Structures & AlgorithmsHardGATE CS · DSA

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

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

Correct answer: D. (3, 4)

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

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

Exams that ask this topic