When a yes-or-no test flips once as a number grows, binary search the number
So far the search ran over data. Sometimes the sorted thing is the answer itself. Koko Eating Bananas is on Netflix's tag list (1 source), and one Netflix candidate reports an easy binary search question in a phone screen (1 report). Here's that shape in a log pipeline.
A job has five batches of log files, with sizes [30, 11, 23, 4, 20]. A worker processes up to rate files an hour, from one batch at a time. An hour on a batch with fewer than rate files left finishes that batch, and the rest of the hour goes unused. What's the slowest rate that finishes everything within 6 hours?
Predict
Batches of 30, 11, 23, 4 and 20 files, and the job must finish in 6 hours. What's the slowest rate that does it?
A batch of b files takes ⌈b/rate⌉ hours: b divided by the rate, rounded up. hours(rate) adds that up over the batches. Here it is for some rates, with a yes or no for each: does this rate finish in 6 hours or less?
Rate
Hours
6 or less?
1
88
no
2
45
no
3
31
no
15
8
no
20
7
no
22
7
no
23
6
yes: the first
30
5
yes
Rates 1 to 30: does the rate finish in 6 hours or less?
no for rates 1 to 22, yes from 23 on
noyes
A faster rate never needs more hours. So the answer is no for every rate up to 22, and yes for every rate from 23 on. It flips exactly once.
That's all binary search needs. The yes and no answers form a sorted list, no, no, ..., no, yes, ..., yes, and you want the first yes. You never build that list. You work out each entry when the search looks at it.
How to spot it: the question asks for the smallest or largest number such that something is possible, such as a capacity, a speed, a time limit or a threshold. And moving the number one way never makes it impossible. Name the test, argue out loud that it flips once, and set bounds where you know the answer on each side.
The test needs hours, and hours needs to round up. Do it in integers: // rounds down, so -(-b // rate) rounds the negative down and flips it back up.