Binary search on the answer: the monotonic check
1 Easier to check than to answer
Packages wait on a dock in a fixed order. A ship takes them away, one trip a day, and a day's load must not weigh more than the ship's capacity. No package is split, skipped or loaded ahead of the ones before it. We want the smallest capacity that ships everything within 3 days. These are the packages for the whole lesson:
No formula gives the answer, because where each day ends depends on the capacity. The opposite question is easy. For a given capacity, say 5, we can load the ship day by day and count the days in one pass.
Binary search on the answer turns that easy question into the answer. We guess a capacity, check it, and throw away half of the capacities left. The loop is the one from the last lesson, run over possible answers instead of indexes.
2 The check: is capacity c enough?
The check loads each day as full as it can. It puts packages on the ship until the next one does not fit, and that package starts a new day. Capacity c is enough if the count of days is 3 or fewer.
Here is the check at capacities 5 and 6. The days take turns in two colours, and the label under each package names its day:
At capacity 5, day 1 takes 3 and 1. The 2 would make the load 6, so it waits for day 2. At capacity 6, the 2 fits on day 1, and every later day starts one package further along the line.
A fuller day leaves fewer packages for the days after it, so loading each day as full as it can never costs a day. The check's count is the fewest days that capacity can manage.
3 Every answer in a row of no and yes
Now we run the check on every capacity from 3 to 13, written under each box. The top row is the days it needs, and the row below is the check's answer:
This is the picture from the last lesson. There, the boxes were indexes of a sorted array. Here, they are possible answers, and the question is the check. The answers still read no, no, and then yes to the end. The first yes, at capacity 6, is the answer.
The answers flip only once because more capacity never needs more days. Capacity c + 1 can follow the plan that capacity c used, since every day's load still fits. So the top row only goes down. Once it reaches 3, it stays at 3 or below.
A check with this property is monotonic: once it says yes, every bigger value says yes too. To spot one, ask whether a more generous value surely works whenever a smaller one does.
4 The range, and the search
The row needs two ends, and each needs a reason:
lis the smallest value that could work. No capacity below the heaviest package can carry it, solstarts at 3.ris a value that surely works. A ship that holds the total, 13, carries everything on day 1, sorstarts at 13.
r must be a sure yes, not a large guess. The invariant says every value from r on says yes, and the loop never checks r itself. In the last lesson, a pretend box past the end of the array played this part. Here, a real answer does.
Each step checks mid and keeps the half where the first yes must be:
The same run as a trace table:
| step | l | r | mid | days at mid | ≤ 3? | move |
|---|---|---|---|---|---|---|
| 1 | 3 | 13 | 8 | 2 | yes | r = 8 |
| 2 | 3 | 8 | 5 | 4 | no | l = 6 |
| 3 | 6 | 8 | 7 | 2 | yes | r = 7 |
| 4 | 6 | 7 | 6 | 3 | yes | r = 6 |
| end | 6 | 6 | return 6 |
The search ran the check four times for eleven capacities. It never asked about 3 or 4. The no at 5 ruled them out, because the answers never flip back.
5 The code
The loop is the last lesson's lowerBound with two changes. l and r start at the ends of the range, and the question for mid is the check. The check gets its own function, daysNeeded.
On our packages, every tab returns 6 for 3 days, 13 for 1 day and 3 for 6 days. For three packages of 10⁹ each and 1 day, it returns 3 × 10⁹.
That last answer does not fit in 32 bits. With 10⁵ packages of up to 10⁹ each, the total can reach 10¹⁴, far past the 32-bit limit of about 2.1 × 10⁹. So r, mid, the load and the result need 64 bits. The last lesson's l + (r - l) / 2 matters here too. With speeds up to 10⁹ in 32 bits, l + r can pass the limit.
C++
Use long long for l, r, mid and load. An int total past 2.1 × 10⁹ wraps around to a wrong value without any error. load + weights[i] is safe, because load is already a long long.
Use long for l, r, mid and load. An int total past 2.1 × 10⁹ wraps around to a negative number without any error.
Nothing to do. Python's integers grow as needed, so a total of 10¹⁴ is fine.
Nothing to do here. Numbers stay exact up to about 9 × 10¹⁵, so a total of 10¹⁴ is safe. Math.floor keeps mid a whole number.
int is 64 bits on today's machines, so a total of 10¹⁴ fits. The built-in max needs Go 1.21 or later.
Convert before adding. Each weight becomes an i64 before it joins r or load. An i32 sum past 2.1 × 10⁹ overflows.
Use long for l, r, mid and load. An int total past 2.1 × 10⁹ wraps around to a negative number without any error.
6 Cost
The check is one pass over the packages, so it costs O(n). The loop runs it once for every halving of the range. A range of 10¹⁴ capacities shrinks to one in about 47 halvings, because 2⁴⁷ is about 10¹⁴. So the search costs O(n log R), where R is the size of the range. At n = 10⁵, that is about 50 checks of 10⁵ steps, or 5 × 10⁶ steps in all. It keeps a few variables, so the extra space is O(1).
The plain way tries every capacity from the heaviest package up, until one is enough. That can mean 10¹⁴ checks:
A range ten times wider costs only about three more checks. So r can always be a generous sure yes.
7 The largest answer instead of the smallest
Some problems ask for the largest value that works. Three balls go on a line at some of the positions 1, 2, 4, 7 and 9, and the smallest gap between two balls should be as large as possible. The check asks whether every gap can be at least d. A bigger d is harder to keep, so this time the answers run yes and then no:
The answer is the last yes, at d = 3. We do not need a second template for it. We ask the opposite question, "is d too big?", and its answers read no and then yes. The same loop finds the first d that is too big. The answer sits just before it, so we return l - 1.
The ends follow the same two rules. Any two positions are at least 1 apart, so l starts at 1. A gap of 9 is wider than the whole line, from 1 to 9, so it is surely too big, and r starts at 9. The loop stops at l = 4, and the answer is 3.
When the answer is a real number, such as a distance of 2.5, there is no next value for l = mid + 1. The loop sets l = mid or r = mid, and runs a fixed number of rounds, such as 100. Each round halves the range, so 100 rounds go far past any precision a problem asks for.
8 Mistakes, and when to use it
- A check that is not monotonic. "Exactly 3 days" says yes only at capacity 6, because capacity 7 needs just 2. The loop checks 8, 11 and 12, hears no each time, and returns 13. "3 days or fewer" is the monotonic check.
lbelow the heaviest package. The check then loads a package that does not fit. On weights[1, 5]with 2 days, starting atl = 1returns 1. The check puts the 1 on day 1 and the 5 on day 2, and never asks whether 5 fits.rthat is not a sure yes. The even share, 13 / 3 = 4, looks like a goodr. But capacity 4 needs 4 days. The loop checks 3, hears no, and returns 4, because it trustsrwithout checking it.- A 32-bit total. Three packages of 10⁹ weigh 3 × 10⁹ in all. A 32-bit sum wraps around, and the search returns a wrong capacity.
- Returning
lfor the largest answer. On the balls,lstops at 4, the first gap that is too big. The answer isl - 1, which is 3.
The sign is an answer we cannot calculate directly, but a guessed value is quick to check. Three shapes come up:
- The smallest value that is enough. The value can be a capacity, an eating speed, a number of days or a divisor. A bigger value only makes the check easier.
- The largest value that still works. The largest smallest gap is one, and a square root rounded down is another. Ask the opposite question and return
l - 1. - The smallest possible largest part. This comes up when an array is split into parts, or books are shared among students. A limit on each part turns it into a check that counts the parts, like the ship's days.
Practice it
- Sqrt(x)Easy
- Koko Eating BananasMedium
- Magnetic Force Between Two BallsMedium
- Split Array Largest SumHard
- Nth root of a numberMedium
- Find the Smallest Divisor Given a ThresholdMedium
- Minimum Number of Days to Make m BouquetsMedium
- Capacity To Ship Packages Within D DaysMedium
- Kth Missing Positive NumberEasy
- Aggressive cowsHard
- Book allocationHard
- Painter's partitionHard
- Minimize Max Distance to Gas StationHard
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.