Binary search on the answer: the monotonic check

Video lessonComing soon

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:

301122133435
weights, in the order they leave the dock. 13 in all

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:

3day 11day 12day 21day 23day 33day 4
Capacity 5: 4 days, so no
3day 11day 12day 11day 23day 23day 3
Capacity 6: 3 days, so yes

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:

53444536272829210211212113no3no4no5yes6yes7yes8yes9yes10yes11yes12yes13
Top: days needed at each capacity. Below: 3 days or fewer?

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.

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:

Every capacity10¹⁹Binary search5 × 10⁶about 1 second
Steps at n = 10⁵ and a range of 10¹⁴, on a scale where each mark is ten times the last

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:

yes1yes2yes3no4no5no6no7no8no9no1no2no3yes4yes5yes6yes7yes8yes9answerl
Top: can every gap be at least d? Below: is d too big?

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.
  • l below the heaviest package. The check then loads a package that does not fit. On weights [1, 5] with 2 days, starting at l = 1 returns 1. The check puts the 1 on day 1 and the 5 on day 2, and never asks whether 5 fits.
  • r that is not a sure yes. The even share, 13 / 3 = 4, looks like a good r. But capacity 4 needs 4 days. The loop checks 3, hears no, and returns 4, because it trusts r without 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 l for the largest answer. On the balls, l stops at 4, the first gap that is too big. The answer is l - 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.
Before searching on the answer, say three things: the check in one sentence, the smallest value that could work, and a value that surely works. Then make sure a bigger value can never turn a yes into a no.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.