Data Structures & AlgorithmsVery hardProduct company OA

A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed?

A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed?
def search(a, x):
    lo, hi, steps = 0, len(a) - 1, 0
    while lo < hi and steps < 50:
        steps += 1
        mid = (lo + hi) // 2
        if a[mid] <= x: lo = mid
        else: hi = mid - 1
    return lo, steps
a = [1, 3, 5, 7, 9, 11]
print(search(a, 3), search(a, 7), search(a, 11))
  1. A. (0, 50) (3, 3) (4, 50)
  2. B. (1, 2) (3, 3) (5, 3)
  3. C. (0, 50) (3, 3) (5, 3)
  4. D. (1, 50) (3, 3) (4, 50)

Correct answer: A. (0, 50) (3, 3) (4, 50)

With mid = (lo + hi) // 2 and the update lo = mid, once hi = lo + 1 the midpoint equals lo; if a[mid] ≤ x, lo does not move and the loop never ends. x = 3: lo 0, hi 5 → hi 1 → mid 0 → lo stays 0 forever. x = 7 happens to finish at index 3. x = 11 reaches lo 4, hi 5 and sticks. The fix is the upper midpoint mid = (lo + hi + 1) // 2 whenever the branch is lo = mid.

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

Exams that ask this topic