Lesson 132 of 296
Binary search on the answer
What you will learn
- Searching over possible answers instead of array positions
- Recognising these problems
- Koko Eating Bananas
- Capacity to Ship Packages Within D Days
On this page
The idea
Some problems ask for the smallest (or largest) value that works: the minimum speed, capacity, time or size. If:
- you can check quickly whether a given value works, and
- once a value works, every bigger value also works (the condition is monotonic),
then binary search over the range of possible answers for the first value that works. The check is usually O(n), so the total is O(n log range).
speed: 1 2 3 4 5 6 7 ...
works? no no no yes yes yes yes
^ binary search finds thisKoko Eating Bananas
Problem (LeetCode 875): piles of bananas; Koko eats at speed k bananas per hour, one pile at a time (if a pile has fewer than k, she finishes it and waits for the next hour). Find the minimum k to finish all piles within h hours.piles = [3, 6, 7, 11], h = 8 → 4.
- Answer range: at least 1, at most the largest pile (eating faster cannot help).
- Check: hours needed at speed k = sum of
ceil(pile / k). Works if<= h. - Monotonic: a faster speed never needs more hours.
function hoursNeeded(piles: number[], speed: number): number {
let hours = 0;
for (const pile of piles) hours += Math.ceil(pile / speed);
return hours;
}
function minEatingSpeed(piles: number[], h: number): number {
let low = 1;
let high = Math.max(...piles);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (hoursNeeded(piles, mid) <= h) high = mid;
else low = mid + 1;
}
return low;
}This is the lower bound template from Lesson 131: find the first speed where the check is true.
Time: O(n log m), where m is the largest pile. (Math.max(...piles) can fail for extremely large arrays; use a loop or reduce in that case.)
Capacity To Ship Packages Within D Days
Problem (LeetCode 1011): packages must be shipped in order. Each day the ship carries packages up to a capacity. Find the minimum capacity to ship everything within days days.weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5 → 15.
- Range: at least the heaviest package (otherwise it can never be shipped), at most the total weight (everything in one day).
- Check: simulate greedily: fill each day until the next package would exceed capacity, then start a new day.
function daysNeeded(weights: number[], capacity: number): number {
let days = 1;
let load = 0;
for (const w of weights) {
if (load + w > capacity) {
days++;
load = 0;
}
load += w;
}
return days;
}
function shipWithinDays(weights: number[], days: number): number {
let low = Math.max(...weights);
let high = weights.reduce((a, b) => a + b, 0);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (daysNeeded(weights, mid) <= days) high = mid;
else low = mid + 1;
}
return low;
}Recognising these problems
- "Minimum speed / capacity / time / size such that ..."
- "Maximum minimum ..." or "minimise the largest ..." (for example, split an array into k parts minimising the largest sum: LeetCode 410).
- A brute force that tries every possible answer one by one.
How to say it in an interview
"When a problem asks for the minimum value that satisfies a condition, and the condition is monotonic, meaning once a value works all larger values also work, I binary search over the range of possible answers. I write a feasibility check, usually an O(n) simulation, and use the lower-bound template to find the first value that passes, giving O(n log range). For Koko the range is 1 to the largest pile and the check sums ceiling divisions; for shipping it is the heaviest package to the total weight with a greedy day count."
Key words
| Word | Meaning |
|---|---|
| Answer space | The range of possible answers |
| Feasibility check | A function that says whether a value works |
| Monotonic condition | Once true, it stays true for all larger values |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.