RecapDifficulty: Advanced1 min

Recap: Modified Binary Search

Name the predicate, check that it changes once, decide whether you want the first true or the last, and round mid to match.

Modified binary search applies wherever a yes-or-no predicate over a range of candidates changes only once, whether the candidates are indices, builds or possible answers. Naming the predicate comes first, then checking that it is monotone, then deciding whether the answer is the first true or the last; that decision fixes the moves, and the moves fix the rounding:

The forms of the search and what each needs
Search forPredicateMovesmid roundedLoop
First trueFalse, then trueTrue: high = mid; false: low = mid + 1Downlow < high
Last trueTrue, then falseTrue: low = mid; false: high = mid − 1Uplow < high
A value in a rotated arrayWhich half is sortedKeep the half that holds the targetDownlow ≤ high
Smallest answer that worksThis answer is feasibleAs first true, over the answersDownlow < high
Largest answer that worksThis answer is feasibleAs last true, over the answersUplow < high

The search makes O(log n) tests, each costing whatever the predicate costs, which over answers is usually a pass over the input: O(n log m). The loop that never ends comes from pairing low = mid with a rounded-down mid, and a predicate that turns false again after turning true gives a wrong answer with no warning.