Learn the pattern · ~15 min
Binary Search on the Answer
also called parametric search, search the answer space
Don't build the best answer. Guess an answer and check it with a yes/no question, prove that question flips from no to yes only once, then binary-search for the flip.
Reach for it when you read
- +"Minimise the maximum" or "maximise the minimum": the smallest possible largest load or part sum, the largest possible smallest gap.
- +"The minimum speed / capacity / time / days such that everything gets done": the answer is one number, and you're asked for the smallest (or largest) one that is enough.
- +Building the best answer directly is hard, but checking a given answer is a greedy pass, a count or a BFS.
- +The answer's range is huge (10⁹, 10¹⁸) while n is around 10⁵: O(n log V) fits, trying every value doesn't.
- +"The k-th smallest" in a set too big to list (a multiplication table, all pair distances): guess a value, count how many are ≤ it.
Not this one when
- ×Find a position in a sorted array, or a peak by its slope: plain binary search on indices. There's no candidate answer to check.
- ×Shortest or longest contiguous subarray of positive numbers with a sum condition: a sliding window does it in O(n).
- ×The check you can write isn't monotone ("exactly k", "equal to"): a yes at X says nothing about X + 1, so halving throws answers away.
Learn Binary Search on the Answer
First, what does "binary search on the answer" mean?
Plain binary search looks for a position in a sorted array. Here we search the possible answers themselves.
Say the answer is a whole number from 1 to 8, and for any guess you can check "is this enough?". Write the checks in a row: ✗ ✗ ✗ ✓ ✓ ✓ ✓ ✓. Once it says yes, it keeps saying yes, so the row is sorted: all ✗, then all ✓. The answer is the first ✓, and halving finds it: check 4 (✓, so the answer is 4 or less), then 2 (✗), then 3 (✗). The answer is 4, after three checks.
So the technique is: write a check for one guess, make sure its answers flip only once, and binary-search the flip.
The problem
Koko Eating Bananas. Piles [5, 9, 4, 12], and 6 hours. At speed k, each hour Koko picks one pile and eats up to k bananas from it. A pile of 9 at speed 4 takes 3 hours: 4, 4, then 1. What's the slowest speed that finishes within 6 hours?
How do we check one speed?
A pile takes
ceil(pile / k)hours. Add them up; the speed works if the total is at most h.
Try k = 4:
| pile | what happens | hours |
|---|---|---|
| 5 | 4, then 1 | 2 |
| 9 | 4, 4, then 1 | 3 |
| 4 | 4 | 1 |
| 12 | 4, 4, 4 | 3 |
That's 9 hours, more than 6: speed 4 fails.
The code for the check
bool ok(vector<int>& piles, int h, long long k) {
long long hours = 0; // 10⁴ piles × 10⁹ hours overflow an int
for (int p : piles) hours += (p + k - 1) / k; // ceil(p / k)
return hours <= h;
}You don't need to memorise this. It's the table: hours per pile, added up, compared with h.
Why (p + k - 1) / k? Integer division rounds down: 9 / 4 is 2, but Koko needs 3 hours. Adding k − 1 first pushes any leftover over the line: (9 + 3) / 4 = 3, while (8 + 3) / 4 = 2 stays exact.
Fine, but which speed is the answer?
Try every speed, starting at 1:
| k | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| hours | 30 | 16 | 11 | 9 | 7 | 6 | 6 | 6 | 5 | 5 | 5 | 4 |
| ok? | ✗ | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
The first ✓ is at k = 6, so the answer is 6. We don't need to go past 12: at speed 12 (the biggest pile) every pile takes one hour.
The brute force
That table is the brute force:
int minSpeedSlow(vector<int>& piles, int h) {
long long k = 1;
while (!ok(piles, h, k)) k++;
return k;
}Piles can hold 10⁹ bananas, so it may try up to 10⁹ speeds, each one a pass over 10⁴ piles. That's 10¹³ steps: just 10⁵ speeds took 0.7 s, so all 10⁹ would take about two hours. Time limit exceeded.
The one thought that fixes it
Stop at k = 6. It works: 6 hours. What does that tell us about k = 7?
- Pile by pile, a faster speed never needs more hours. The 9 takes 2 hours at speed 6 and 2 at speed 7. The 12 takes 2 and 2.
- So 7 also finishes within 6 hours, and so does 8, and every speed after it.
- The other way round: k = 5 fails with 7 hours, and every slower speed takes at least as long, so they all fail.
So the bottom row is ✗ … ✗ ✓ … ✓: it flips only once. That's the sorted row from the start, and binary search finds its first ✓ in about 30 checks instead of 10⁹.
That single flip is the whole precondition. Change the question to "finishes in exactly 5 hours" and the row becomes ✓ only at 9, 10 and 11. Check the middle, 6: ✗ (6 hours). Is the answer left or right of it? 5 gives 7 hours and 9 gives 5, so you can't tell, and halving throws answers away. Before you binary-search, make sure a ✓ at x means a ✓ at every bigger x.
int minEatingSpeed(vector<int>& piles, int h) {
long long lo = 1, hi = *max_element(piles.begin(), piles.end());
while (lo < hi) { // lo might work, hi surely works
long long mid = lo + (hi - lo) / 2;
if (ok(piles, h, mid)) hi = mid; // works: the answer is mid or smaller
else lo = mid + 1; // fails: the answer is bigger
}
return lo;
}lo = 1, because speed 0 would divide by zero. hi = 12, the biggest pile: every pile takes one hour, and the problem promises h is at least the number of piles, so hi surely works.
Dry run
Same piles, h = 6.
| lo | hi | mid | hours | what happens |
|---|---|---|---|---|
| 1 | 12 | 6 | 6 | ✓: the answer is 6 or smaller, hi = 6 |
| 1 | 6 | 3 | 11 | ✗: the answer is bigger than 3, lo = 4 |
| 4 | 6 | 5 | 7 | ✗: bigger than 5, lo = 6 |
| 6 | 6 | lo = hi: stop, 6 |
Speed 6, the same answer as the brute force, after 3 checks instead of 6.
Why it's O(n log V)
Count the checks and what each costs. The speeds from 1 to V (the biggest pile) halve every check, so there are about log₂ V of them: 30 for V = 10⁹. Each check is one pass over the n piles. That's 30 × 10⁴ = 3 × 10⁵ steps: O(n log V) time, O(1) space.
From 10¹³ steps down to 3 × 10⁵, by halving the range of answers instead of trying each one.
Ship within D days? New check, same frame
Capacity To Ship Packages Within D Days: weights 1, 2, …, 10 must ship in order within D = 5 days. What's the smallest ship capacity? Only the check changes. Load each day greedily, and start a new day when the next package doesn't fit:
bool canShip(vector<int>& weights, int D, int cap) {
int days = 1, load = 0;
for (int w : weights) {
if (load + w > cap) { days++; load = 0; } // doesn't fit: next day
load += w;
}
return days <= D;
}A bigger ship never needs more days, so it flips once. lo = 10, the biggest package (it must fit), and hi = 55, everything in one day. The checks go 32 (2 days ✓), 21 (3 ✓), 15 (5 ✓), 12 (6 ✗), 14 (6 ✗), and the answer is 15.
Maximise the minimum? Find the last ✓
Magnetic Force Between Two Balls: positions [1, 2, 3, 4, 7], put m = 3 balls in them, and make the smallest gap between two balls as big as possible. The check for a gap d: sort the positions, put a ball on the first, then on the next position at least d further, and so on; ok if you placed 3.
| d | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| balls placed | 5 | 3 | 3 | 2 | 2 | 2 |
| ok? | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ |
Now the row is ✓ … ✓ ✗ … ✗, and we want the last ✓. Flip the two moves, and round mid up:
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2; // round up
if (ok(mid)) lo = mid; // works: the answer is mid or bigger
else hi = mid - 1;
}Why round up? With lo = 2, hi = 3, rounding down gives mid = 2, it works, lo = 2 again, forever. Here lo = 1, hi = 6, and the loop checks 4 (✗), 2 (✓), 3 (✓): the answer is 3.
Remember this
- "Minimise the maximum", "maximise the minimum", "the smallest speed / capacity / days such that…": binary search on the answer.
- Try every answer in your head first. If checking one answer is easy and the ✓s come in one block, binary-search the block's edge.
- The check must flip only once. "Exactly k" checks don't.
- Pick
lo(could work) andhi(surely works). Searching for the last ✓, roundmidup. - Use 64-bit for sums inside the check.
Practise it on Koko Eating Bananas, then Capacity To Ship Packages Within D Days (greedy packing), Minimum Number of Days to Make m Bouquets (a time check), Magnetic Force Between Two Balls (the last ✓), Split Array Largest Sum and Path With Minimum Effort (the check is a BFS).
Below, watch Koko Eating Bananas run line by line.
Watch it work, line by line
Koko Eating Bananas ↗, piles = [3, 6, 7, 11], h = 8 → 4. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
Break it
Each card changes one line of the template the way it usually goes wrong in an interview. Before you open it, guess what the broken version prints.
hi = mid → hi = mid - 1 (drop mid even when it works)
on piles = [30, 11, 23, 4, 20], h = 6
What goes wrong?
hi = mid → hi = mid - 1 (drop mid even when it works)broken → 22
correct → 23
mid = 23 needs 6 hours, so it works, and it's the answer. hi = 22 throws it away, every speed left (16 to 22) fails, and the loop returns 22, which needs 7 hours. On the hook's chapters this bug still prints 4, by luck: test on more than one input.
lo = mid + 1 → lo = mid (keep mid even when it fails)
on piles = [3, 6, 7, 11], h = 8
What goes wrong?
lo = mid + 1 → lo = mid (keep mid even when it fails)broken → never ends: lo = 3, hi = 4, mid = 3 forever
correct → 4
With lo = 3 and hi = 4, mid rounds down to 3. Speed 3 fails, lo = mid sets lo to 3 again, and nothing changes. A failed mid must leave the range.
while (lo < hi) → while (lo <= hi)
on piles = [3, 6, 7, 11], h = 8
What goes wrong?
while (lo < hi) → while (lo <= hi)broken → never ends: lo = hi = 4 forever
correct → 4
When lo = hi = 4 the loop runs once more: mid = 4 works, hi = mid sets hi to 4 again. lo <= hi belongs to the other template, the one with ans = mid; hi = mid - 1. Don't mix the two.
hours <= h → hours < h
on piles = [3, 6, 7, 11], h = 8
What goes wrong?
hours <= h → hours < hbroken → 6
correct → 4
Speeds 4 and 5 finish in exactly 8 hours, which is allowed. With < they count as fails, and the first speed under 8 hours is 6 (6 hours).
(p + k - 1) / k → p / k (round down instead of up)
on piles = [3, 6, 7, 11], h = 8
What goes wrong?
(p + k - 1) / k → p / k (round down instead of up)broken → 3
correct → 4
At speed 3 the 7-page chapter counts as 2 hours and the 11-page one as 3, so speed 3 looks like 1 + 2 + 2 + 3 = 8 hours. Really it's 10: a started hour is a used hour.
When to use it, and when not
Ask yourself
Is the answer a number I could guess? If someone handed me a guess X, could I check it quickly? And if X works, does every bigger (or every smaller) X work too?
Reach for it when
- +minimise the maximum / maximise the minimum
- +answer range is numeric and large
- +a greedy check for a fixed X is obvious
- +answer up to 1e9-1e18 -> ~30-60 checks
- +check runs in O(n) or O(n log n)
It fails 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
Looks like it, isn't (and the other way round)
- Split Array Largest Sum looks like Interval DP, needs this pattern
DP over partitions works (O(k n2)), but 'minimise the largest' points to binary search with greedy check.
- Kth Smallest Element in a Sorted Matrix looks like K-way Merge, needs this pattern
Heap works, but binary search on the value with a staircase count is often better.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What two things must be true to binary-search the answer?Reveal
Checking a fixed X is fast, and the check is monotone: once true, it stays true as X grows (or the reverse).
2Minimise, and
ok(mid)is true. Which bound moves?Revealhi = mid. mid works, so it stays in the range as a possible answer.3Why
mid = lo + (hi - lo + 1) / 2when maximising?RevealWith
lo = mid, rounding down leaves lo unchanged whenhi = lo + 1, so the loop runs forever. Rounding up always moves.
Practice ladder
- 1Koko Eating Bananasthe hookMedium
- 2Capacity To Ship Packages Within D Daysgreedy packingMedium
- 3Minimum Number of Days to Make m Bouquetstime checkMedium
- 4Magnetic Force Between Two Ballsmaximise the minimumMedium
- 5Split Array Largest Sumgreedy packingHard
- 6Factory Machinestime checkMedium
- 7Kth Smallest Number in Multiplication Tablecount checkHard
- 8Path With Minimum Effortgraph checkMedium
Finished Binary Search on the Answer? Mark it done and Lessgo moves you to the next step.