26/41
Part 5 of 7 · On the answerLearn and do

The search is the same loop, with hours(mid) <= h as the test

With hours written, the search is the loop from before.

def hours(rate, batches):
    # ceil(b / rate) in integers
    return sum(-(-b // rate) for b in batches)


def slowest_rate(batches, h):
    # at max(batches), every batch takes one hour
    lo, hi = 1, max(batches)
    while lo < hi:
        mid = (lo + hi) // 2
        # fast enough: the answer is mid or slower
        if hours(mid, batches) <= h:
            hi = mid
        # too slow: the answer is faster than mid
        else:
            lo = mid + 1
    return lo


print(slowest_rate([30, 11, 23, 4, 20], 6))
23

It's the loop you wrote by hand, with hours(mid) <= h in place of times[mid] >= target. Here are its looks with h = 6:

lohimidhours(mid)move
130158too slow: lo = 16
1630236fast enough: hi = 23
1623198too slow: lo = 20
2023217too slow: lo = 22
2223227too slow: lo = 23

Five calls to hours found 23. Trying 1, 2, 3 and up takes 23 calls.

The bounds are part of the answer. hi = max(batches) is a rate that surely works, as long as h is at least the number of batches. If it isn't, no rate works, and that's the clarifying question to ask.

Each call to hours is O(n) for n batches, so the search costs O(n log m) for a largest batch of m. On 1,000 batches of up to 10,000 files with 1,500 hours, counting up from 1 called hours 5,082 times and took 207.6 ms. The binary search called it 13 times and took 0.60 ms.

Since Python 3.10, bisect can run this search for you, because False sorts before True. bisect_left(range(1, max(batches) + 1), True, key=lambda rate: hours(rate, batches) <= 6) + 1 returned 23. In an interview, the written loop is clearer.

In the editor, write least_capacity(weights, d) with the same search. It prints the least capacity that ships eight packages in three days.