Python 3D Academyবাংলা

Binary search on the answer: the smallest load that is enough

🌍 In real life. A courier company must send a row of parcels from Dhaka to Chattogram, in the order they were booked, within 5 days. Each day one van goes, carrying parcels until the next one would go over its limit. A bigger van costs more, so the manager wants the smallest daily load that still finishes in time.

There is no sorted list to search here. But the possible answers are a sorted range: the load could be 10, 11, 12, … up to the total weight. And they have the same shape as Lesson 43.2's test: too small, too small, …, enough, enough, because a bigger van never needs more days. So binary search can look for the first "enough".

The idea in one sentence: when you can check whether a guess is good enough, and every answer above a good one is also good, binary search the range of possible answers for the smallest good one.

Its words:

  • feasibility check: a function that answers "is this guess good enough?", here days_needed(…) <= days
  • monotonic: once the check says yes, it says yes for every bigger guess too; this is what makes the range sorted
  • search space: the range of possible answers, from the smallest that could work to the biggest you'd ever need

Step by step:

  1. the range: at least the heaviest parcel (smaller, and it never fits), at most the total weight (everything in one day)
  2. lo = max(weights), hi = sum(weights); while lo < hi: mid = (lo + hi) // 2
  3. run the check on mid: enough? The answer is mid or smaller: hi = mid
  4. not enough? It and everything below it are too small: lo = mid + 1
  5. lo == hi is the smallest load that is enough

Watch the parcels fall into days for each guess:

Why it is correct. It is Lesson 43.2's boundary search, with the check as the test. The check is monotonic: if a van of size c finishes in time, a van of size c + 1 can take exactly the same parcels each day, so it finishes in time too. So the answers go not enough … not enough, enough … enough, and the first "enough" is the smallest load that works. The range starts wide enough: below the heaviest parcel nothing works, and at the total weight it always does.

What it costs, by counting. With n parcels and total weight S, the range holds about S answers, so binary search makes about log₂ S guesses, and each guess runs a check over all n parcels: O(n log S). Trying every load one by one would be O(n × S). For 100 parcels of 1000 kg each, that is about 17 checks instead of up to 99,000.

Where else it works. Any "smallest x that is enough" or "biggest x that still fits" with a monotonic check: the slowest eating speed that finishes in time, the square root of a number (the biggest x with x × x ≤ n), the fewest machines for a job.

def days_needed(weights, cap):
    days, load = 1, 0
    for w in weights:
        if load + w > cap:          # this parcel waits for the next day
            days += 1
            load = 0
        load += w
    return days

def least_capacity(weights, days):
    lo, hi = max(weights), sum(weights)
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(weights, mid) <= days:
            hi = mid                 # enough: maybe something smaller is too
        else:
            lo = mid + 1             # too small, and so is everything below
    return lo

parcels = [3, 2, 2, 4, 1, 4]
print(least_capacity(parcels, 3), days_needed(parcels, 6), days_needed(parcels, 5))
print(least_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))
print(least_capacity([1000] * 100, 7))

Mistakes and edge cases.

  • starting lo at 0 or 1: a load below the heaviest parcel never fits it, and a check that doesn't notice will say a parcel can be split; start at max(weights)
  • < days instead of <= days: finishing in exactly the allowed days is fine; the strict check gives an answer that is too big
  • a check that isn't monotonic: binary search on the answer only works when "enough" never turns back into "not enough" for a bigger guess
  • reordering the parcels: the order is fixed; sorting them would answer a different question

Quiz

  1. What does this print?

    def days_needed(weights, cap):
        days, load = 1, 0
        for w in weights:
            if load + w > cap:          # this parcel waits for the next day
                days += 1
                load = 0
            load += w
        return days
    
    print(days_needed([5, 1, 4, 2, 3], 6), days_needed([5, 1, 4, 2, 3], 15))
  2. Why can binary search look for the smallest load at all?

    • A bigger load never needs more days, so the answers go not enough … enough
    • Because the parcels are sorted
    • Because the days are a whole number
  3. Why does the search start at lo = max(weights) and hi = sum(weights)?

    • Below the heaviest parcel nothing works; at the total weight everything fits in one day
    • Those are the first and last parcels
    • Binary search always starts at the smallest and biggest items
  4. least_capacity([3, 2, 2, 4, 1, 4], 3) should be 6, but it gives 9. Which line is wrong?

    def least_capacity(weights, days):
        lo, hi = max(weights), sum(weights)
        while lo < hi:
            mid = (lo + hi) // 2
            if days_needed(weights, mid) < days:
                hi = mid
            else:
                lo = mid + 1
        return lo
  5. n parcels with a total weight S. What does least_capacity cost?

    • O(n log S): about log S guesses, each checking n parcels
    • O(log n)
    • O(n × S)

Coding tasks

  1. Write days_needed(weights, cap): the parcels leave in order, and each day takes parcels until the next one would go over cap (every parcel is at most cap). Return how many days it takes.

  2. Write least_capacity(weights, days): the smallest daily load that sends every parcel, in order, within days days. days_needed is given: binary search the answers and call it for each guess, at most 60 times even when the total weight is 100,000.