Builds onBinary search
01The idea
You cannot always compute the answer with a formula, but you can check a guess. "Can the job finish in 10 minutes?" is easy to test, even when "what is the shortest time?" is hard.
If the check has one more property, you can binary search the answer itself. The property is that once a guess works, every bigger guess works too. Then the guesses split into a block of "no" followed by a block of "yes", and you want the first "yes". That is the same boundary search as in the binary search lesson. The range is now a range of possible answers instead of indices in an array.
The recipe has three parts:
- Write
enough(x), a function that says whether the answer x works. - Pick a range
lotohithat contains the answer.lois the smallest answer that could work.hiis one you know works. - Binary search for the first x where
enough(x)is true.
The cost is the cost of one check times the number of checks. With a range of size R, you need about log₂ R checks. So a range of a billion needs only about 30 checks.
02How to spot it
Binary search on the answer fits when:
- the problem asks for the smallest or largest value that meets a condition: the minimum speed, the minimum capacity, the largest distance, the fewest days
- checking one candidate value is easy, such as one pass with a greedy rule
- making the candidate bigger can only help, or can only hurt
A good test is to ask whether 2x works whenever x works. If yes, the check is monotonic, and the search is safe.
Pay attention to the range. A wrong hi that does not work makes the search return a wrong value. Pick hi from a case you can reason about, such as one worker doing everything.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue