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?- A. 37 7
- B. 37 100
- C. 36 7
- 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
- Problem: Sort values by increasing frequency; values with the same frequency go in decreasing order. python from collections import…
- Problem: A researcher's h-index is the largest h such that at least h papers have ≥ h citations each. python def hindex(c): c = sorted(c…
- Problem: A 3 × 4 matrix is sorted row-wise and each row starts after the previous row ends. Search it as one virtual sorted array of R·C…
- Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded. python def…
- Problem: Reorder the letters of s so that letters listed in order appear in that order; letters not in order go last, keeping their…
- Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i]…