Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Binary search

Search the answer, not the array: halve a monotone predicate until one candidate is left.


When it applies

not enoughworks first feasible answer lo and hi close in, halving each time check is monotone: once true, always true

Binary search applies whenever a yes/no test is monotone: once it turns true it stays true. That covers the obvious case of a sorted array, and the less obvious one where the answer is a number and checking a candidate is cheaper than constructing it.

Signals: "minimum capacity", "smallest k such that", "maximise the minimum", "first index where". Write the check first, prove it is monotone, then search.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

lo, hi = low_bound, high_bound
while lo < hi:                  # invariant: the answer is in [lo, hi]
    mid = (lo + hi) // 2
    if feasible(mid):
        hi = mid                # mid might be the answer; keep it
    else:
        lo = mid + 1            # mid is too small
return lo

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.