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?- A. 5 5
- B. ('stuck', 0, 30) 5
- C. ('stuck', 5, 6) 5
- 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
- Problem: n ≤ 2·10⁵ meetings [s, e); choose the maximum number of non-overlapping ones. Compare three greedy orders: by end time, by start…
- Problem: A road network has weights 1..5 (n, m ≤ 2·10⁵). A candidate solution runs plain BFS and sets dist[v] = dist[u] + w the first time…
- Problem: Each link succeeds with a probability; find the most reliable path from 0 to 3 (maximise the product). Dijkstra works with a…
- Problem: Board game on squares 1..n: roll a die (1–6); landing on the foot of a ladder or the head of a snake moves you to its other end…
- Problem: Find the bug: Kahn's algorithm is used to schedule build steps, but nobody checks whether a cycle exists. What does it return for…
- Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports…