Binary Search
When to use: sorted data, or any monotonic predicate ok(x) (false…false true…true). "Minimize the maximum" / "smallest capacity such that …" → binary search on the answer.
One template to rule them all — find the first index where ok is true:
lo, hi = 0, n # answer in [lo, hi]; hi = "none found"
while lo < hi:
mid = (lo + hi) // 2
if ok(mid): hi = mid # mid could be the answer
else: lo = mid + 1
return lo
ok: F F F T T T
lo ^first T hi
Pitfalls: in Java use lo + (hi - lo) / 2; make sure each branch shrinks the range.
Problems
Showing 23 of 23