Data Structures & Algorithms / Module 4: Searching and sorting
Topic 4.2
Binary search on the answer
Finding an answer by halving its range, as long as the 'is it enough?' question flips only once.
Watch: every capacity guess throws away half the options, because if one capacity works, every bigger one must work too.
- moving now
- being checked
- passed / marked
- finished / the result
- no longer used
The problem
Packages weighing 3, 2, 2, 4, 1, 4 must be shipped in order, within 3 days at most. The truck leaves once a day. What is the smallest capacity that works? There is no list to search. What we have is a question: "with capacity X, how many days does it take?"
Why binary search works here
The key is an ordered property, often called monotonic:
- A bigger capacity never needs more days.
- So if 6 works, 7, 8 and so on must work too.
- If 5 doesn't work, 4 can't work either.
Picture all the capacities in a row: no, no, no, yes, yes, yes… We want the first "yes". That is exactly ordinary binary search: look at the middle, then drop the half that must be wrong.
Code, for programmersFind the smallest capacity that works
function daysNeeded(weights, cap) {
let days = 1, load = 0;
for (const w of weights) {
if (load + w > cap) { days++; load = 0; } // truck is full: next day
load += w;
}
return days;
}
function smallestCapacity(weights, maxDays) {
let lo = Math.max(...weights); // must fit the heaviest package
let hi = weights.reduce((a, b) => a + b, 0); // everything in one day
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (daysNeeded(weights, mid) <= maxDays) hi = mid; // works: maybe smaller works too
else lo = mid + 1; // too slow: need bigger
}
return lo;
}How fast it is
If the range of answers is R and one check takes n steps, trying them one by one costs R × n. With binary search it is only log₂(R) × n. For a range of a million capacities, that is about 20 checks, not a million.
Where this pattern shows up
- The biggest batch size that still fits in memory.
- The fewest servers needed to clear a queue within a time limit.
git bisect: the first commit that breaks a test. Everything before passes, everything after fails.- The highest image quality whose file size is still under a limit.
Quiz
What is the main condition for binary search on the answer?
Capacity 6 works for 3 days. What is certainly true?
The answers range from 1 to 1,000,000. Roughly how many checks does binary search need?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.