The pattern
Normal binary search hunts for a value in a sorted array. This pattern searches something else entirely: the range of possible answers.
It applies when the question has this shape:
- The answer is a number in a known range, say 1 to 10^9.
- You can write a function
feasible(x)that returns true or false. feasibleis monotonic: once it becomes true it stays true as x
increases (or the mirror image).
If those hold, the answers look like false false false TRUE true true, and binary search finds the boundary in O(log range) calls to feasible.
Recognise it from: minimum such that, maximum such that, smallest speed / capacity / size that still works.