Data Structures & AlgorithmsHardHCLTech · Wipro pattern

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

  1. A. (7, 7)
  2. B. (7, 9)
  3. C. (6, 8)
  4. D. (7, 8)

Correct answer: D. (7, 8)

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 7 and last index 8.

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

Exams that ask this topic