iq.lab
Python starts when a code cell comes near or you run one
06 Sorting and binary search

Lesson 3 of 4

Binary search on the answer

Some questions ask for the smallest number that makes something possible, such as a speed, a capacity or a time. When a yes-or-no check on one guess switches from no to yes exactly once, binary search finds that number among a billion candidates with about 30 checks.

About 1 hour 30 minutes, with the 2 problems worked in it
By the end you can
  • Write a check that answers "does this value work?" with one walk over the input

  • Tell whether a check switches from no to yes exactly once as the value grows

  • Binary search a range of answers for the first value that works, with the right lo and hi

  • State the cost as one check times about log₂ of the range size

  • Recognize the pattern in a problem that never mentions sorting or searching

A backfill has to reload five daily partitions, in date order, over three nights. They hold 4, 2, 3, 5 and 1 million rows. Each nightly run has a row cap: it loads whole partitions, in order, and stops before the one that would push it over the cap. What is the smallest cap that finishes in three nights?

For any one cap, you can answer "does it work?" by acting out the schedule. With a cap of 5 (million rows), the first night loads the 4 (adding the 2 would make 6), the second loads the 2 and the 3, the third loads the 5, and the 1 needs a fourth night: one too many. With a cap of 6, the nights load 4 and 2, then 3, then 5 and 1: three nights. A cap below 5 cannot load the 5 at all, so the answer is 6.

Nothing here is sorted, and there is no list to search. Yet binary search from the previous lesson (check the middle of a sorted range, throw away the half that cannot hold the answer) finds the cap, and finds it fast when the cap could be anywhere up to a billion. The trick is to search the range of possible answers, running the yes-or-no check at each guess. We build it on a simpler check first, then come back to the backfill.

Is this speed fast enough?

What does a check look like? Start with a classic whose check is one line of arithmetic per item: Koko eating bananas.

Koko has three piles of bananas: 3, 6 and 7. She has h = 6 hours. She picks a speed k, a whole number: the most bananas she eats in one hour. Each hour she eats from one pile only: k bananas, or the rest of the pile if fewer are left. What is the slowest speed that finishes in 6 hours?

The check asks: at speed k, how many hours do the piles take? A pile of 7 at speed 3 takes three hours: 3, then 3, then the last 1. That last hour is not full, but it still uses up the hour. So one pile takes pile / k hours, rounded up.

Python's // divides and rounds down: 7 // 3 is 2. To round up with whole numbers, add k - 1 before dividing. (7 + 2) // 3 is 9 // 3, which is 3. Any leftover, even one banana, plus k - 1 reaches the next multiple of k, so the result goes up by one hour. When nothing is left over, the extra k - 1 falls short of the next multiple, so nothing changes: (6 + 2) // 3 is 8 // 3, still 2.

The trace adds up the hours for all three piles at speed 3. Before you step through, work out each pile's hours by hand.

Step throughHours at one speed
Step 1 of 15
Line 1 is about to run.
def hours_needed(piles, speed):
total = 0
for pile in piles:
hours = (pile + speed - 1) // speed
total += hours
return total
Names
no names yet
Output
(nothing printed yet)

The check is one walk over the piles: O(n) time for n piles and O(1) extra space. You will often see the same walk on one line, sum((pile + speed - 1) // speed for pile in piles). That is a generator expression from module 1: a comprehension inside a call, with its square brackets dropped.

Rounding is where this check goes wrong, so test yourself on it.

PredictRounding down versus rounding up

Each line prints a pile's hours at speed 3 twice: first rounded down with //, then rounded up. Type exactly what it prints.

speed = 3
for pile in [6, 7, 1]:
    print(pile // speed, (pile + speed - 1) // speed)

Answers that switch once

Which speeds work? Run the check at every speed from 1 to 7:

speed k1234567
hours_needed(k)16965543
within 6 hours?nonoyesyesyesyesyes

Read the bottom row: no, no, then yes from speed 3 on, and never no again. That is no accident. Eating faster never takes more hours: raising k can only shrink each pile's rounded-up hours or leave them the same. So once a speed works, every faster speed works too, and the slowest speed that works is 3.

The brute force (the plain approach that tries every possibility) reads that row from the left and stops at the first yes:

def min_eating_speed(piles, h):
    speed = 1
    while hours_needed(piles, speed) > h:   # too slow: try the next speed
        speed += 1
    return speed

It is correct, and on big inputs it is hopeless. The answer can be as large as the biggest pile, and every check walks every pile: O(n · m) time for n piles and a biggest pile of m. The full problem allows 104 piles of up to 109 bananas each. That is up to 109 checks of 104 piles: 1013 steps. At roughly 10 million (107) simple steps per second, that is 106 seconds, more than eleven days.

Now read the bottom row as a list: False, False, True, True, True, True, True. It has the shape of has_column in the previous lesson: every no comes before every yes, so the row is sorted, and finding the first True in a sorted row is a binary search. We never build the row. Each time the search wants an entry, one check computes it.

Not every yes-or-no question switches once, and telling which ones do is most of the skill.

Quick checkWhich answers switch once?

Let x take the values 1, 2, 3, and so on. Which of these yes-or-no questions switch from no to yes exactly once, and then stay yes for every bigger x? Pick every one that does.

Choose every option that applies, then check.

Searching the speeds

How do we binary search a range of numbers instead of a list? The previous lesson's first-true template finds the first index where a yes/no answer turns to yes. Here it is again, with speeds in place of indexes. Two names mark the speeds that could still be the answer: lo, the slowest, and hi, the fastest. We write the range as lo..hi: every whole number from lo to hi, both included.

The range starts at lo = 1 and hi = max(piles). Speed 1 is the slowest there is; speed 0 eats nothing. At speed max(piles) every pile takes one hour. The problem guarantees at least as many hours as piles (each pile needs an hour of its own, so with fewer hours no speed could work), so hi always works.

This hi is a real answer, not "none". In the previous lesson hi started at the length, one past the last index, because the list might hold no yes at all. Here a yes is guaranteed, so the search needs no extra slot for "none".

Each pass checks the middle speed, mid = (lo + hi) // 2:

  • If mid works, the answer is mid or slower: hi = mid. mid stays in the range, since it might be the answer.
  • If mid is too slow, so is every speed below it: lo = mid + 1.

The loop runs while lo < hi, and when they meet, one speed is left: the answer. Before you step through, guess which speeds the search checks, and in what order.

Step throughBinary search over the speeds
Step 1 of 49
Line 1 is about to run.
def hours_needed(piles, speed):
total = 0
for pile in piles:
total += (pile + speed - 1) // speed
return total
def min_eating_speed(piles, h):
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if hours_needed(piles, mid) <= h:
hi = mid
else:
lo = mid + 1
return lo
Names
no names yet
Output
(nothing printed yet)

The loop always stops, for the reason the previous lesson gave. While lo < hi, mid is at least lo and less than hi. So hi = mid moves hi down, and lo = mid + 1 moves lo up. Every pass shrinks the range by about half, until one speed is left. A range of m speeds therefore takes about log₂(m) checks, where log₂(m) is the number of times m can be halved before it reaches 1.

The promise is the proof. It starts true: no speed is below lo = 1, and speed max(piles) works. hi only moves onto a speed that works. lo only moves past mid when mid fails, and every slower speed fails too, because the answers switch once. When one speed is left, it works and every speed below it fails, so it is the answer.

Halving makes the checks few. Here 7 speeds took 3 checks, the same as the brute force: on a range this small, halving barely helps. With piles of up to a billion bananas, the brute force can need a billion checks; binary search needs at most 30, because 230 is more than a billion. With 104 piles, that is 30 × 104 = 300,000 steps, about 0.03 seconds.

Work it outHow many checks?

Koko's piles now hold up to 1,000,000 bananas, so the search starts with lo = 1 and hi = 1000000. At most how many checks does the lo < hi loop make before lo == hi? Type a whole number.

checks

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

The loop never mentions bananas. Only the check and the range belong to Koko. Put the general loop together:

Put in orderThe loop that never changes

Build first_yes(lo, hi, works), which returns the smallest x from lo to hi for which works(x) is True. You may assume works(hi) is True and the answers switch once.

works is a function passed in as an argument, the way sorted(words, key=len) passes len; works(mid) calls it and gets True or False. Indentation is part of each line. Two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • else:
    • mid = (lo + hi) // 2
    • while lo <= hi:
    • def first_yes(lo, hi, works):
    • while lo < hi:
    • lo = mid + 1
    • hi = mid - 1
    • hi = mid
    • return lo
    • if works(mid):

    Now write Koko from a blank editor. Write hours_needed first, run it on one speed by hand, then wrap the search around it.

    mediumBinary search target 25 min

    Koko eating bananas

    Koko has piles of bananas: pile i holds piles[i] bananas, and she has h hours to clear them all. Before she starts, she fixes a whole-number speed k: the most bananas she eats in one hour.

    An hour belongs to one pile. During it she eats k bananas from that pile, or whatever is left of it if that is fewer than k. If the pile runs out early, the rest of the hour goes unused: she starts the next pile only in the next hour. So a pile of 7 at speed 3 takes three hours: 3, then 3, then 1.

    Return the slowest speed k at which she clears every pile within h hours.

    Example 1
    Inputpiles = [3, 6, 7], h = 6Output3

    At speed 3 the piles take 1 + 2 + 3 = 6 hours. At speed 2 they take 2 + 3 + 4 = 9, too many.

    Example 2
    Inputpiles = [10, 4], h = 2Output10

    Two piles in two hours means one hour per pile, so the speed must cover the bigger pile.

    Example 3
    Inputpiles = [7, 7, 7], h = 20Output2

    Speed 1 takes 21 hours, one too many. Speed 2 takes 4 + 4 + 4 = 12.

    Constraints
    • 1 ≤ len(piles) ≤ 104

    • len(piles) ≤ h ≤ 109, so some speed always works

    • 1 ≤ piles[i] ≤ 109

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Two bugs catch people here: rounding down, and starting lo at 0. Rounding down says a pile of 5 at speed 2 takes 2 hours, when it takes 3 (2, 2, then 1). Starting lo at 0 can check speed 0 and divide by zero: once hi reaches 1, mid is (0 + 1) // 2 = 0. The reference solution also defines hours_needed inside min_eating_speed, so the check reads piles from the outer function and needs only the speed.

    Recap. The check answers yes or no for one speed with one pass over the piles. The answers switch once, so the lo < hi loop finds the first yes in about log₂(m) checks, starting from the smallest possible answer and one that surely works.

    A check that remembers: shipping in order

    What if one step of the check depends on the steps before it? Koko's check works out each pile's hours on its own and adds them up. In some checks, what happens to the next item depends on what is already loaded. Back to the backfill. It is a classic problem in another costume: packages wait on a conveyor belt in a fixed order, a ship sails once a day, and its capacity is the most weight it can carry. What is the smallest capacity that ships every package within days days? The partitions are the packages, and the nights are the days.

    The check: at one capacity, how many days does the ship need? Load greedily, which means taking the move that looks best right now and never undoing it: keep adding the next package while it fits, and when it does not, start a new day with it. Two names do the work: used, the days started so far, and load, the weight on today's ship.

    The trace runs the check at capacity 6 on the backfill's numbers. Before you step through, predict which packages make used go up.

    Step throughDays needed at capacity 6
    Step 1 of 26
    Line 1 is about to run.
    def days_needed(weights, capacity):
    used = 1
    load = 0
    for w in weights:
    if load + w > capacity:
    used += 1
    load = 0
    load += w
    return used
    Names
    no names yet
    Output
    (nothing printed yet)

    "At most the capacity" means the test is >, not >=. A load equal to the capacity is allowed, which is why the 2 joined the 4 at exactly 6.

    Greedy gives the fewest days. Each day ships a run of neighbors, starting where the last day stopped. Greedy takes everything that fits, so after every day it is at least as far along the belt as any other loading could be, and it never needs an extra day.

    Run the check yourself at three capacities.

    PredictDays at three capacities

    Run the greedy check at three capacities. Type exactly what this prints.

    def days_needed(weights, capacity):
        used = 1
        load = 0
        for w in weights:
            if load + w > capacity:
                used += 1
                load = 0
            load += w
        return used
    
    for capacity in [5, 7, 12]:
        print(capacity, days_needed([3, 2, 4, 1, 2], capacity))
    

    The capacities switch once too: a bigger ship never needs more days. Any day's load that fits a small ship also fits a bigger one, so the bigger ship could copy the small ship's days exactly, and greedy needs no more days than that copy. For the backfill's numbers and 3 days:

    capacity5678910
    days_needed433322
    within 3 days?noyesyesyesyesyes

    The search loop is Koko's, with days_needed(weights, mid) <= days as the check. The range is the new part. Speed 1 made sense for Koko; capacity 1 does not. The ship must lift the heaviest package, so lo = max(weights). And one day that carries everything always works, so hi = sum(weights). The promise in the frame card above needs every package to fit on an empty ship, and starting at max(weights) guarantees it. See what happens without it:

    Quick checkStarting the range too low

    A teammate starts the shipping search at lo = 1 instead of lo = max(weights). Everything else stays: hi = sum(weights), the same loop, and days_needed from the trace.

    What does the search return for weights = [1, 5] and days = 2?

    Choose one answer, then check.

    Run the whole search once by hand, the way you would at a whiteboard with no run button.

    On paperRun the shipping search by hand

    On paper, find the smallest capacity that ships [3, 2, 4, 1, 2] within 2 days. Use the lo < hi search with lo = max(weights) and hi = sum(weights), and run days_needed by hand at each mid. For each pass, write lo, hi, mid, the days the check counts, and what moves. Reveal one step at a time to check.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    smallest capacity

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    Now write it yourself: the greedy check first, then the search with the new range.

    mediumBinary searchGreedy choice target 25 min

    Smallest ship capacity

    Packages wait on a conveyor belt in a fixed order; package i weighs weights[i]. A ship sails once a day. Each day it carries the next few packages from the front of the belt, and their total weight must be at most the ship's capacity, the most weight it can carry. Packages cannot be split or reordered.

    Return the smallest capacity that ships every package within days days.

    Example 1
    Inputweights = [4, 2, 3, 5, 1], days = 3Output6

    Capacity 6 ships [4, 2], then [3], then [5, 1]. Capacity 5 needs four days: [4], [2, 3], [5], [1].

    Example 2
    Inputweights = [3, 3, 3, 3], days = 2Output6

    Capacity 6 ships two packages a day: [3, 3] and [3, 3]. Capacity 5 fits only one 3 at a time, so it needs four days.

    Example 3
    Inputweights = [7, 1, 1, 1], days = 4Output7

    The ship must lift the 7 at some point, and capacity 7 already finishes in two days.

    Constraints
    • 1 ≤ days ≤ len(weights) ≤ 5 · 104

    • 1 ≤ weights[i] ≤ 500

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Same loop, new check, new range. Koko searched speeds from 1 to the biggest pile with an arithmetic check; shipping searches capacities from the heaviest package to the total weight with a greedy walk. Each check is one O(n) pass, so the cost is O(n log s) for a total weight of s.

    Do not sort the packages. The belt order is fixed, and sorting changes the answer: [1, 5, 1] in 2 days needs capacity 6 ([1, 5], then [1]), while the same weights sorted, [1, 1, 5], would need only 5 ([1, 1], then [5]).

    Spotting it in a new costume

    How do you know to reach for this when the problem says nothing about searching? The two problems share three signals:

    1. The question asks for the smallest number that makes something possible: a speed, a capacity, a time, a limit.
    2. For one guess, a walk answers "does this work?"
    3. The answers switch once: making the number bigger never turns a yes into a no.

    Then pick the range. lo is the smallest value that could possibly work, and hi is a value that surely works. The cost is one check times about log₂ of the range size.

    Some problems ask for the largest value that still works. Then the answers run yes, then no. Flip the question so they run no, then yes, and step back one from the first yes. For the largest whole x with x × x at most 50, ask "is x × x more than 50?" instead: no up to 7, yes from 8. The search finds 8, so the answer is 7.

    Here is a costume you have not seen. The problem never mentions searching; ask the three questions before you write a line.

    Code itMinutes until the batch is done

    A batch of files files is shared by workers running side by side. Worker i needs minutes[i] minutes per file, so after t minutes it has finished t // minutes[i] files.

    Write min_minutes(minutes, files), the smallest whole number of minutes t after which the workers have finished at least files files between them. With minutes = [2, 3] and 5 files, after 6 minutes the workers have finished 3 + 2 = 5 files, and after 5 minutes only 2 + 1 = 3, so the answer is 6.

    There is at least one worker, every minutes[i] is at least 1, and files is at least 1. The last test is large: trying t = 1, 2, 3, ... in order is too slow.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    The module's practice bank has one more: Split into k pieces (LeetCode 410, hard). It cuts a list into k runs of neighbors so that the largest run sum is as small as possible. Ask the three questions before you open the hints.

    Last, answer that rationale probe the way you would in the room.

    Say itNothing is sorted, so why binary search?

    You have solved the shipping problem, and the interviewer asks: "Nothing in this problem is sorted. Why does binary search work here, and what does it cost?" Write what you would say, in a few plain sentences.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Intervals