Data Structures & AlgorithmsHardProduct company OA · Infosys pattern

Binary search finds the index of the minimum of the rotated sorted array [15, 18, 22, 3, 6, 9, 12] using: mid = (lo + hi) / 2; if a[mid] > a[hi] then lo = mid + 1 else hi = mid; stop when lo == hi. What index is returned, and how many loop iterations run?

  1. A. index 3, 2 iterations
  2. B. index 4, 3 iterations
  3. C. index 0, 3 iterations
  4. D. index 3, 3 iterations

Correct answer: D. index 3, 3 iterations

lo=0, hi=6: mid 3, a[3] = 3 ≤ 12 → hi = 3. lo=0, hi=3: mid 1, 18 > 3 → lo = 2. lo=2, hi=3: mid 2, 22 > 3 → lo = 3 = hi. Three iterations, returning index 3. Stopping as soon as a[mid] is the minimum (after the first probe) gives '2 iterations', but this loop only stops when lo == hi. Comparing with a[hi] (not a[lo]) is what makes the rule work for both rotated and unrotated arrays.

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

Exams that ask this topic