Pattern

Binary search

Halve a sorted or monotonic search space on every step to find a target, a boundary, or the smallest value that works.

What it is

Binary search repeatedly cuts a search space in half by testing its midpoint, discarding the half that can't contain the answer. It needs the space to be monotonic: some condition that's false, then true (or vice versa) as you move across it, whether that space is literally a sorted array or something more abstract like "every possible eating speed" or "every possible time value." Each iteration removes half the remaining candidates, so it reaches a single answer in logarithmic time even over a search space of billions.

When it applies

Tells in the problem

The classic mistake

Using mid = (lo + hi) // 2 with hi = mid instead of hi = mid - 1 (or the reverse) is the classic way to get the loop bounds or midpoint update wrong in a way that either infinite-loops or off-by-one skips the answer, when the update doesn't match the invariant being maintained. This happens because there are several valid binary-search templates (closed range vs. half-open, searching for a value vs. searching for a boundary) and mixing pieces from two of them produces code that looks plausible but loops forever on a two-element array. Catch it by writing down, before coding, exactly what lo and hi mean at each point ("the answer is somewhere in [lo, hi]" or "[lo, hi)") and keeping every update consistent with that statement.

Questions to start with

All 13 binary search questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.