Binary Search
Halve the search space each step, on arrays and on answers.
5 pages, free to read
- 1
Classic binary search
BeginnerIn a sorted array, compare the target with the middle element and throw away the half that cannot contain it, so you find any value in O(log n) steps.
8 min read - 2
Lower & upper bound
IntermediateLower bound finds the first index whose value is >= target and upper bound finds the first index whose value is > target, which gives first and last positions, counts and insert points in O(log n).
9 min read - 3
Rotated sorted arrays
IntermediateA rotated sorted array is two sorted runs glued together; at every mid point at least one half is still sorted, so you can check that half and keep binary searching in O(log n).
9 min read - 4
Binary search on the answer
AdvancedWhen you can quickly check whether a candidate answer is good enough, and goodness only flips once as the candidate grows, binary search over the range of possible answers instead of over an array.
11 min read - 5
Searching a sorted matrix
IntermediateIf the whole matrix reads as one sorted list row by row, binary search it as a flat array in O(log(m x n)); if only rows and columns are each sorted, walk a staircase from a corner in O(m + n).
9 min read