Loading section...

Binary Search on Monotonic Predicates

Concepts: pyMonotonicPredicate, pyUniversalBinarySearch

Every binary search problem you have ever solved is a special case of this: find the smallest x in the search space such that predicate(x) is True, where predicate is monotonic (False...False...True...True with no True-False-True pattern). This is the most general form. Once you see it this way, you will never again ask 'can I binary search this?' -- you will just check if the predicate is monotonic. The Universal Template Notice that standard binary search (find leftmost position of target) is predicate(x) = (nums[x] >= target). The template finds the smallest x where nums[x] >= target, which is the first occurrence if it equals target, or the insertion point if it does not. This is exactly what bisect_left computes. The template and bisect_left are the same algorithm expressed differentl