Data Structures & AlgorithmsHardProduct company OA

Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses mid = (lo + hi) // 2 with lo = mid; the run is capped at 50 iterations.

Problem: Find the bug: binary search for the LAST x in [lo, hi] with ok(x) true (here the largest x with x² ≤ 30). The first version uses mid = (lo + hi) // 2 with lo = mid; the run is capped at 50 iterations.
def last_true(ok, lo, hi, cap=50):
    it = 0
    while lo < hi:
        it += 1
        if it > cap: return "stuck", lo, hi
        mid = (lo + hi) // 2
        if ok(mid): lo = mid
        else: hi = mid - 1
    return lo
def last_true_fixed(ok, lo, hi):
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if ok(mid): lo = mid
        else: hi = mid - 1
    return lo
print(last_true(lambda x: x * x <= 30, 0, 30), last_true_fixed(lambda x: x * x <= 30, 0, 30))
What is printed?
  1. A. 5 5
  2. B. ('stuck', 0, 30) 5
  3. C. ('stuck', 5, 6) 5
  4. D. ('stuck', 5, 6) 6

Correct answer: C. ('stuck', 5, 6) 5

When hi = lo + 1, (lo + hi) // 2 = lo; if ok(lo) is true, lo = mid changes nothing and the loop never ends (here at lo = 5, hi = 6). When the update is lo = mid, round the midpoint UP: (lo + hi + 1) // 2. Then the range always shrinks and the answer ⌊√30⌋ = 5 is found in O(log n).

More Coding Interview Problems questions

Exams that ask this topic