Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Builds 1..100 are tested; every build from some version onward is broken. isbad() is expensive, so find the first bad build with binary search and count the calls.

Problem: Builds 1..100 are tested; every build from some version onward is broken. is_bad() is expensive, so find the first bad build with binary search and count the calls.
calls = 0
def is_bad(v):
    global calls; calls += 1
    return v >= 37
def first_bad(n):
    lo, hi = 1, n
    while lo < hi:
        mid = (lo + hi) // 2
        if is_bad(mid): hi = mid
        else: lo = mid + 1
    return lo
print(first_bad(100), calls)
What is printed?
  1. A. 37 7
  2. B. 37 100
  3. C. 36 7
  4. D. 37 6

Correct answer: A. 37 7

The loop keeps the answer in [lo, hi] and halves it each call: mids 50 (bad), 25, 38 (bad), 32, 35, 37 (bad), 36 → lo = hi = 37 after 7 calls, i.e. ⌈log₂ 100⌉. Linear scanning would need 37 calls. Using lo <= hi with hi = mid would loop forever.

More Coding Interview Problems questions

Exams that ask this topic