Binary search on answer
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Instead of searching a list, you search the range of possible answers: guess a middle value, test whether it works, and halve the range. It works whenever "if size X works, bigger sizes also work".
Practical use cases
- Web app: Smallest truck capacity to ship in 5 days. A logistics site must ship 10,000 parcels in order within 5 days and wants the smallest truck load that works. Trying every capacity is slow. Guess a capacity, simulate the shipping, see if it fits in 5 days, and halve the range; about 19 simulations find the answer.
- Web app: Fair splitting of work among support agents. A helpdesk tool splits 300 tickets in order across 6 agents so the busiest agent has the least work possible. Guess a maximum load, check if 6 agents can handle it, and narrow the guess. Only about nine guesses are needed instead of trying every possible load.
- Web app: Tuning a rate limit or batch size. A queue worker needs the largest batch size that still finishes within a timeout. Testing a middle size and adjusting finds a safe, large batch size in a few trial runs instead of dozens.
- System: Placing things far apart. Planners placing cell towers or servers so the closest two are as far apart as possible guess a distance, check if all fit, and adjust. Each check is quick, so a good layout is found after only a few guesses rather than trying every distance.
The story: Koko and the Guard's Tea Break
Koko the monkey had stolen four piles of bananas from the market: 3, 6, 7 and 11. The guard had gone for tea and would be back in 8 hours. Each hour Koko chose one pile and ate up to s bananas from it. If the pile had fewer, she wasted the rest of that hour. "How slowly can I eat and still finish before he comes back?" she asked.
Mira noticed something odd. Nothing in the piles is sorted. There is no list to search! But the answer (the speed) is a number between 1 and 11, and it has a lovely property: if speed 6 finishes in time, then 7 does too, and 8 and so on. If speed 3 is too slow, so are 2 and 1. The speeds are split into a row of "no, no, no, yes, yes, yes".
That is the smell: "find the minimum (or maximum) value such that something is possible". Whenever you can test one candidate in a quick check, and the results flip only once from no to yes, you can binary search over the answers instead of over the data.
Koko tried speed 6 (yes!), then 3 (no), then 5 (yes), then 4 (yes). Slowest speed: 4. Four guesses instead of eleven.
How to spot this problem, and where you need it
You want the smallest or largest value that satisfies a condition (capacity, time, speed, distance), and checking one candidate value is easy but there are far too many candidates.
Signs you need it
- The question asks for "minimum possible maximum" or "maximum possible minimum", or "smallest X such that it can be done".
- You can write a simple yes/no function: does this value work?
- If a value works, every larger value also works (or the reverse), so the answers flip only once.
Where to use it in a project
- Capacity planning for shipping, queues and workers where you need the smallest size that works.
- Balanced scheduling or splitting of tasks among agents so no one is overloaded.
- Tuning limits, timeouts and batch sizes by guessing and testing a middle value.
The solution
Write the check: given a candidate value, simulate the process and say whether it works. Pick the lowest and highest possible answer. Test the middle value. If it works, the answer is that or smaller, so keep the lower half; if not, keep the upper half. Repeat until the range collapses to one value, which is the best answer.
Payoff: Before: trying every capacity from 1 to 500,000. After: about 19 simulations.
Explain it like I am 8
You are finding the smallest bucket size that lets you empty the pond in one afternoon. You do not try every size. You try a middle size: if it is big enough, try a smaller one; if not, try a bigger one. Each try halves the possible sizes.
How it works, step by step
- Clues: "minimum/maximum value such that...", "smallest capacity", "largest minimum distance", "within h hours / d days". Think binary search on the answer.
- Write the range of possible answers: the smallest sensible value (
1) and the largest sensible value (the biggest pile). - Write a checker
canFinish(speed): simulate with this one candidate and return yes or no. - Check the yes/no is monotonic: once it turns yes, it stays yes for bigger values. This makes binary search legal.
- Binary search: if mid works, the answer is mid or smaller (
hi = mid); otherwise it is larger (lo = mid + 1). Stop whenlo == hi.
The code in four languages
PHP
<?php
// Koko Eating Bananas: smallest speed that finishes within $h hours
function minSpeed(array $piles, int $h): int {
$lo = 1; // slowest possible speed
$hi = max($piles); // speed this fast always works (1 hour per pile)
while ($lo < $hi) {
$mid = intdiv($lo + $hi, 2);
$hours = 0;
foreach ($piles as $p) {
$hours += intdiv($p + $mid - 1, $mid); // ceil(p / mid)
}
if ($hours <= $h) {
$hi = $mid; // mid works: try slower
} else {
$lo = $mid + 1; // too slow: need faster
}
}
return $lo;
}
echo minSpeed([3, 6, 7, 11], 8); // 4JavaScript
// Koko Eating Bananas: smallest speed that finishes within h hours
function minSpeed(piles, h) {
let lo = 1; // slowest possible speed
let hi = Math.max(...piles); // speed this fast always works (1 hour per pile)
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
let hours = 0;
for (const p of piles) {
hours += Math.ceil(p / mid); // hours needed for this pile
}
if (hours <= h) {
hi = mid; // mid works: try slower
} else {
lo = mid + 1; // too slow: need faster
}
}
return lo;
}
console.log(minSpeed([3, 6, 7, 11], 8)); // 4Java
public class Main {
// Koko Eating Bananas: smallest speed that finishes within h hours
static int minSpeed(int[] piles, int h) {
int lo = 1; // slowest possible speed
int hi = 0;
for (int p : piles) hi = Math.max(hi, p); // speed this fast always works (1 hour per pile)
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
int hours = 0;
for (int p : piles) {
hours += (p + mid - 1) / mid; // ceil(p / mid): hours needed for this pile
}
if (hours <= h) {
hi = mid; // mid works: try slower
} else {
lo = mid + 1; // too slow: need faster
}
}
return lo;
}
public static void main(String[] args) {
System.out.println(minSpeed(new int[]{3, 6, 7, 11}, 8)); // 4
}
}Go
package main
import "fmt"
// minSpeed is Koko Eating Bananas: the smallest speed that finishes within h hours.
func minSpeed(piles []int, h int) int {
lo := 1 // slowest possible speed
hi := 0
for _, p := range piles {
hi = max(hi, p) // speed this fast always works (1 hour per pile)
}
for lo < hi {
mid := lo + (hi-lo)/2
hours := 0
for _, p := range piles {
hours += (p + mid - 1) / mid // ceil(p / mid): hours needed for this pile
}
if hours <= h {
hi = mid // mid works: try slower
} else {
lo = mid + 1 // too slow: need faster
}
}
return lo
}
func main() {
fmt.Println(minSpeed([]int{3, 6, 7, 11}, 8)) // 4
}Time: O(n log m) · Extra space: O(1). About log of the biggest pile (m) guesses, and each guess checks n piles.
Watch out for
- Setting
hi = mid - 1when mid works, which can throw away the very answer you want. - Trying binary search when the yes/no is not monotonic (it flips back and forth), so halving is not valid.
- Forgetting to round up the hours for a pile: a pile of 7 at speed 3 needs 3 hours, not 2.
Quick check
- Which phrase hints at binary search on the answer?
- "Reverse a linked list"
- "Find the smallest capacity so that everything ships in D days"
- "Count the vowels"
- What must be true about the yes/no results over the candidate answers?
- They flip only once (no...no, yes...yes)
- They alternate
- They are random
- When the test says speed mid works, what do we do?
- lo = mid + 1
- Stop immediately
- hi = mid