Command Palette

Search for a command to run...

← All patterns

Pattern · Search

Binary Search on the Answer

When you can check "is answer x good enough?" and the check is monotonic, binary search over possible answers.

Time O(log(range) × cost of check) · Space O(1)

Taught in Module 11: Binary Search

Think of it like this

Choosing the smallest suitcase that fits everything: if size 50 fits, every bigger size fits too, so you only test sizes by halving.

Clues that point here

  • → "Minimum capacity/speed/time such that..."
  • → "Maximise the minimum" or "minimise the maximum"
  • → A yes/no feasibility check is easy to write
  • → Large answer range (up to 10^9)

Not this pattern when

  • ✕ The feasibility check isn't monotonic
  • ✕ The answer space is tiny (just try all)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Binary Search on the Answer · template
int lo = minPossible, hi = maxPossible;
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (feasible(mid)) hi = mid;      // mid works: try smaller
    else lo = mid + 1;                // mid fails: need bigger
}
return lo;                             // smallest feasible answer

Common versions

  • Koko eating bananas
  • Capacity to ship packages
  • Split array largest sum
  • Minimum days to make bouquets

Practice problems with this pattern

Related patterns