Binary Search on the Answer
O(n log R)
Binary-search the answer value itself; for each guess run a linear feasibility test that's monotonic in the guess.
0/22 solved
Recognise it
The signal
"Minimize the maximum" / "maximize the minimum" / smallest X that's possible, over a large numeric range with an easy check for a guess.
1Brute force
Try every candidate answer, each with a feasibility check.
2The observation
Linear search over the answer: feasibility is monotone so log(range) checks suffice.
3Why it works
feasible(X) is false for X < ans and true for X ≥ ans (or the reverse), so the boundary can be binary-searched.
Reach for it when
- +Prompt says 'minimize the maximum' / 'maximize the minimum' / 'smallest X such that it's possible'.
- +You can write a fast feasibility check
feasible(x)that's monotonic (once true, stays true as x grows). - +The answer is a number in a large range and direct DP/greedy is unclear, but checking a guess is easy.
Not when
- ×Feasibility isn't monotone — a bigger guess can flip back to infeasibleuse Rethink the model; BS will miss the answer
- ×The check for a fixed X is as hard as the original problemuse Direct DP or greedy
- ×You need which elements form the optimum, not just its valueuse Reconstruct after, or DP with choices
- ×Range is tiny or the data itself is sorted (you'd search the array, not the answer)use Plain binary search or greedy
Intuition
Sometimes you can't binary-search the array — but you can binary-search the answer itself.
Read the full intuition
Here's the mental flip. The question "what's the minimum speed Koko needs to eat all bananas in H hours?" hides a much easier question: "Given a fixed speed s, can she finish in time? yes/no." That yes/no is trivial to compute — just simulate. And it's monotonic: if speed 5 works, every speed above 5 works too; if 4 fails, everything below fails. So feasibility looks like NO NO NO YES YES YES as speed climbs — and finding that first YES is a textbook boundary binary search.
So the recipe is always:
- Identify the answer's numeric range
[lo, hi](slowest..fastest, smallest..largest sum…). - Write
feasible(x)— a simple linear check that's monotonic in x. - Binary-search the smallest x with
feasible(x) == True(or largest True, for maximise).
Key idea
You're not searching positions in an array — you're searching values the answer could be. The array's role is just inside
feasible().
The tell in a prompt: "minimize the maximum", "maximize the minimum", "smallest capacity / speed / largest sum such that…", and constraints where the answer lives in a big numeric range you could test point by point.
Why it costs what it costs
Time O(n log R). O(log R) binary-search iterations over the answer range R, each running an O(n) feasibility scan.
Space O(1). only the loop bounds plus whatever the feasibility check uses (usually constant).
Practice
- Koko Eating BananasFoundationFoundationGoogle, UberMedium
- Capacity To Ship Packages Within D DaysApply it · Minimise a capacity with a greedy day count.Apply itAmazon, UberMedium
- Minimum Number of Days to Make m BouquetsOne change · Check counts contiguous runs.One changeMedium
- Split Array Largest SumTwists · Looks like DP over partitions.TwistsGoogle, CitadelHard
- Magnetic Force Between Two BallsBranches · Maximise the minimum instead.BranchesMedium
- Kth Smallest Element in a Sorted MatrixCombine · Answer is a value; check counts elements <= mid.CombineAmazon, CitadelMedium
- Find K-th Smallest Pair DistanceAdvanced · Count pairs with distance <= d.AdvancedHard
- Kth Smallest Number in Multiplication TableMastery checkMastery checkHard
- Sqrt(x)Amazon, AdobeEasy
- Find K Pairs with Smallest SumsCitadel, AmazonMedium
- Path With Minimum EffortGoogle, UberMedium
- Swim in Rising WaterGoogle, CitadelHard
Pitfalls
Classic bugs
- !lo/hi must bracket the answer: split-array largest sum is lo = max(element), hi = sum(all), not hi = max.
- !Max-the-min searches the largest feasible x — mirror the predicate and move lo, not hi.
- !Overflow in the feasibility sum (use 64-bit); float ceil can mis-round — use
(a+b-1)//b. - !Return
lo(== hi) after the loop, not the lastmid. - !Real-valued answers: run a fixed iteration count or to a set precision, not
while lo < hi.
Go deepervariants and techniques · 5 combinations · resources
Variants and techniques
- Aliens Trick (Lagrangian relaxation / WQS binary search)CP 2400+When f(k), the best answer using exactly k groups, is convex in k: drop the k constraint and charge lambda per group. Solve the easier DP with no k dimension, then binary search lambda until the optimum uses k groups. The answer is g(lambda) + lambda*k.
- Parallel Binary SearchCP 2400+When each of q queries needs its own binary search over the time of a sequence of updates, run all the searches together. In each of log T rounds, sort queries by their current mid, replay the updates once, and check every query at its mid.
- Minimise the maximumSearch smallest x with feasible(x)=True, where feasible means 'can keep every group's load ≤ x'. Split Array Largest Sum, Ship Packages.
- Maximise the minimumSearch largest x feasible; feasible = 'can place items keeping every gap ≥ x'. Aggressive cows, magnetic force.
- Rate / speedfeasible(speed) = total time ≤ limit. Koko Eating Bananas.
- On a boolean timelinefeasible(day) = enough resources available by that day. Bouquets, last day to cross.
- Partition / k-th order on two arraysBinary search the cut position rather than a value. Median of Two Sorted Arrays.
Combinations
Binary Search on the Answer+Greedy
minimise the maximum / maximise the minimum over splits, speeds, or capacities
- Binary Search on the Answer:
- turns optimisation into a yes/no question
- Greedy:
- answers the fixed-threshold question in O(n): a greedy fill (split array, ship packages) or a monotone count (Factory Machines: sum of t/k_i >= n)
Split Array Largest SumCapacity To Ship Packages Within D DaysKoko Eating Bananas
Binary Search on the Answer+Graph BFS / DFS
minimise the maximum height/effort along a path
- Binary Search on the Answer:
- fixes a threshold on edge/cell cost
- Graph BFS / DFS:
- checks reachability using only allowed cells
Binary Search on the Answer+Two Pointers
k-th smallest pair distance / k-th in a sorted matrix
- Binary Search on the Answer:
- searches the k-th value
- Two Pointers:
- counts how many pairs/cells are <= mid in linear time
Find K-th Smallest Pair DistanceKth Smallest Element in a Sorted Matrix
K-way Merge+Binary Search on the Answer
k-th smallest in a sorted matrix / sorted pair sums
- K-way Merge:
- frontier heap pops k times
- Binary Search on the Answer:
- alternatively binary search the value with a count
Kth Smallest Element in a Sorted MatrixFind K Pairs with Smallest Sums
Parallel Binary Search+Union-Find (Disjoint Set)
for each pair, the first time it becomes connected as edges are added
- Parallel Binary Search:
- every query binary searches the day on which its pair connects
- Union-Find (Disjoint Set):
- replay the edge additions once per round