Binary Search · Pattern 7 of 8

Binary search on the answer

The most important pattern for interviews. You cannot find the answer directly, but you can check a guess. If "k works" means every bigger (or smaller) k also works, binary search the guess.

5 variations · 18 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • "Minimum speed / capacity / days such that …" or "maximum distance / size such that …"
  • Checking one candidate is a simple greedy pass over the input
  • The answer is a number in a known range, often up to 10⁹

The template

Binary Search on Answer Space
// smallest value that works; works() goes false ... false, true ... true
int minFeasible(int lo, int hi) {
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (works(mid)) hi = mid;       // works: try smaller
        else lo = mid + 1;              // too small
    }
    return lo;
}

// largest value that works; works() goes true ... true, false ... false
int maxFeasible(int lo, int hi) {
    while (lo < hi) {
        int mid = lo + (hi - lo + 1) / 2;   // round up because we set lo = mid
        if (works(mid)) lo = mid;           // works: try bigger
        else hi = mid - 1;                  // too big
    }
    return lo;
}

// Koko: works(k) = total hours at speed k <= h, searched over [1, max pile]

The variations

  1. 1Minimise: the smallest value that works

    Slowest speed, smallest capacity, fewest days, smallest divisor, the smallest "largest part". Guess mid, run a greedy check, keep the left half when it works.

  2. 2Maximise: the largest value that works

    Largest minimum distance, largest tastiness, most tasks. The check flips: true, true, … false. Round mid up and keep the right half when it works.

  3. 3Count to find the kth

    The kth smallest value is the smallest x with at least k values ≤ x. Counting values ≤ x in a sorted matrix or a multiplication table is a quick O(n) walk.

  4. 4Real-valued answers

    When the answer is a decimal (a distance, a line position), binary search on doubles for a fixed number of rounds, keeping the same works / does-not-work logic.

    Now you solve
  5. 5Math in the check

    The check is a formula rather than a pass over an array: the smallest k with 1 + 2 + … + k ≥ target, or a base whose digit sum equals n.

    Worked example Reach a Number Medium Read the solution
    Now you solve

Mistakes to avoid

  • Picking the wrong range: the low end must be a possible answer (often 1 or the max element), the high end one that surely works (the sum, the max).
  • A check that is not monotonic. Say out loud why "k works" implies "k + 1 works" before you code.
  • Summing hours or pieces in an int: the total can pass 2³¹. Use long.
  • Real-valued answers: loop a fixed 60–100 times, or until hi − lo < 1e-6, instead of lo < hi.
Next: Binary search on a partition →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.