Binary Search on the Answer
A book club has four chapters to read, of 30, 12, 25 and 8 pages, and six evenings to do it. The rule: each evening you read at most p pages, and only from one chapter, so a 25-page chapter at 10 pages an evening takes three evenings. What is the slowest pace that still finishes on time? There is no sorted list anywhere in sight, yet this is a binary search problem.
The rule
If "can it be done with x?" flips only once, binary search x.
Ask the yes-or-no question for every possible pace. A pace of 1 page an evening: no. A pace of 30: certainly yes. And once a pace works, every faster pace works too. So the answers, in order of pace, form a row that flips once from no to yes, and the slowest working pace is the first yes. That is the first_true template from the last lesson, searching over paces instead of positions:
def evenings_needed(chapters, pace):
return sum((pages + pace - 1) // pace for pages in chapters) # rounds up
def slowest_pace(chapters, evenings):
return first_true(1, max(chapters),
lambda pace: evenings_needed(chapters, pace) <= evenings)(pages + pace - 1) // pace divides and rounds up, because a half-used evening still counts as an evening. The search range runs from 1 to the longest chapter: at that pace every chapter takes one evening, and reading faster cannot help.
Each check costs one pass over the chapters, and there are about log₂ of the range checks. For 100,000 chapters and a longest chapter of a billion pages, that is about 30 passes instead of trying a billion paces.