Ship all packages in D days: what exactly do you binary search?
Question
A warehouse ships packages from a belt. weights lists them in belt order. Each day one truck takes the next packages in order, up to the truck's capacity in total weight. You can't split or reorder packages.
Write least_capacity(weights, days): the smallest capacity that ships everything within days days.
weights = [4, 8, 2, 7, 3, 5, 1] least_capacity(weights, 3) # 12 least_capacity(weights, 1) # 30 least_capacity(weights, 7) # 8
def least_capacity(weights, days): ...
Show hints (3)
- "TEST ONE CAPACITY"
Forget the search for a moment. Given one capacity, say 10, can you count the days it needs? Fill each day until the next package doesn't fit.
- "WHAT GROWS"
If capacity 12 works in 3 days, does 13 work too? Write yes or no for every capacity from 8 to 30. What shape does that list have?
- "THE RANGE"
The answer is at least
max(weights), or the heaviest package never fits. It is at mostsum(weights), which ships everything in one day. Binary search that range for the first yes.
Show checked explanation
Binary search over capacities, not over the list. If a capacity works, every bigger one works too. So search from max(weights) to sum(weights) for the first capacity that works. To test one capacity, fill each day greedily and count the days. The total is O(n log(sum - max)).
def least_capacity(weights, days): def fits(capacity): used, load = 1, 0 for weight in weights: if load + weight > capacity: used, load = used + 1, 0 load += weight return used <= days lo, hi = max(weights), sum(weights) while lo < hi: mid = (lo + hi) // 2 if fits(mid): hi = mid else: lo = mid + 1 return lo print([least_capacity([4, 8, 2, 7, 3, 5, 1], d) for d in (1, 3, 7)])
[30, 12, 8]
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
First, test one capacity. Fill each day in belt order until the next package doesn't fit, then start a new day. With capacity 12 you get [4, 8], [2, 7, 3], [5, 1]: 3 days, so 12 works. With capacity 11 you get [4], [8, 2], [7, 3], [5, 1]: 4 days, so 11 doesn't.
Filling greedily is safe. Taking a package today when it fits never makes a later day worse. It only leaves fewer packages for later.
More capacity never needs more days. So the yes/no answers for capacities 8, 9, ..., 30 form a sorted list: a run of "no", then only "yes". You want the first "yes". That is the same search as finding the first value that is at least a target.
| step | lo | hi | mid | days at mid | move |
|---|---|---|---|---|---|
| 1 | 8 | 30 | 19 | 2 | fits, so hi = 19 |
| 2 | 8 | 19 | 13 | 3 | fits, so hi = 13 |
| 3 | 8 | 13 | 10 | 4 | too many, so lo = 11 |
| 4 | 11 | 13 | 12 | 3 | fits, so hi = 12 |
| 5 | 11 | 12 | 11 | 4 | too many, so lo = 12 |
Now lo == hi == 12. When mid fits, it may be the answer, so hi = mid keeps it. When it doesn't fit, nothing at or below it can work, so lo = mid + 1.
The range held 23 capacities, and 5 tests were enough. A plain scan up from 8 also needs 5 here. But with 1 day the answer is 30, and the scan tests all 23. The binary search never needs more than 5. Each test walks all n packages once, so the total is O(n log(sum - max)).
Common mistakes
- Starting the search at
lo = 1. A capacity below the heaviest package can't ship it, but the day count doesn't notice. With 7 days you get 4, and no truck of 4 can carry the 8. - Starting a new day with
load = 0and dropping the package that didn't fit. That package is never counted, so the answer comes out too small: 9 instead of 12. - Sorting the packages first. The belt order is fixed, and order changes the answer. For
[1, 5, 1]in 2 days the answer is 6, but sorted it would be 5. - Binary searching the indexes of
weights. The answer is a capacity, and it usually isn't in the list. Here 12 is not a weight.
Follow-up questions
- "How do you spot this pattern in other tasks?" The task asks for the smallest or largest value that makes something possible. Checking one value is easy, and the yes/no answers change only once as the value grows. Examples: the slowest reading speed that finishes a book on time, or the largest gap you can keep between k routers placed along a street.
- "How many tests for 100,000 packages of up to 500 kg each?" The capacities run from at most 500 up to at most 50,000,000. Halving that range takes at most 26 tests. Each test is one pass over 100,000 packages, so about 2.6 million steps in all.
- "What if
daysis 0 or the list is empty?" Check that first. With no packages,max(weights)raisesValueError. Withdays = 0, no capacity works, but the search never finds out. It returnssum(weights), 30 here. Raise an error instead.
What a strong answer covers
Names what is searched (capacity) and why the yes/no answers are sorted. Gives the range max(weights) to sum(weights) with reasons. Tests one capacity greedily in O(n). Checks bad input.
Open in interactive practice deck →