Binary search on sorted arrays
When data is sorted, one look at the middle tells you which half cannot hold the answer. Throw that half away and repeat: about log₂ n looks instead of n. Most problems here are one question in disguise: where is the first index where a yes/no test turns from no to yes?
How to recognise it
- The array is sorted (or sorted by some key), and n is large enough that O(n) per query is too slow.
- The question asks for the first or last position of something, a count of equal values, or where a value would be inserted.
- Each index answers a yes/no test, and all the "no" answers come before all the "yes" answers.
- The array is not sorted, but comparing a middle value with its neighbour still tells you which side to keep (as in Find Peak Element).
The idea in one picture
Guess a number from 1 to 100 when the only hint is "higher" or "lower". The best first guess is 50, because whatever the reply, half the numbers are gone. Binary search does exactly that on a sorted array: look at the middle, keep the half that can still hold the answer, repeat.
The yes/no view
Most binary search problems can be turned into one question. Write a test that every index answers with no or yes, so that all the no answers come first:
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| nums | 1 | 3 | 3 | 5 | 8 | 9 |
| test: nums[i] ≥ 4 | no | no | no | yes | yes | yes |
The answer is the first yes, index 3. Lower bound, upper bound, insert position, first and last position and counting are all this one search with a different test.
Lower bound: the template behind most of them
lo = 0, hi = n # the answer is somewhere in lo..hi; n means "no yes at all"
while lo < hi:
mid = lo + (hi - lo) / 2
if test(mid): hi = mid # mid is a yes: the first yes is mid or to its left
else: lo = mid + 1 # mid is a no: the first yes is to its right
return lo
When the loop ends, lo equals hi and points at the first yes, or at n if there is none.
| Problem | Test |
|---|---|
| Lower bound, Search Insert Position | nums[i] ≥ x |
| Upper bound | nums[i] > x |
| First and last position | lower bound of x, and upper bound of x minus 1 |
| Count occurrences | upper bound minus lower bound |
| Single element in a sorted array | at an even index i, nums[i] ≠ nums[i + 1] |
Exact match: the classic template
When you only need "is it there, and where", the classic form stops as soon as it finds the value:
lo = 0, hi = n - 1
while lo <= hi:
mid = lo + (hi - lo) / 2
if nums[mid] == target: return mid
if nums[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
Do not mix the two forms. lo < hi goes with hi = mid, and lo <= hi goes with hi = mid - 1.
Common mistakes
- Mixing the templates, as in
while lo <= hiwithhi = mid, which can loop forever. - Starting
hiatn - 1in the lower-bound template, so "every value is too small" can never be answered. - Writing
(lo + hi) / 2in Java or C++ where both can be large. - Using
<in the test when the question needs≤, which finds the wrong end of a run of equal values.
Problems
- Binary Searcheasyguide ready
- Search Insert Positioneasyguide ready
- Lower Boundmediumguide ready
- Upper Boundmediumguide ready
- Floor and Ceil in Sorted Arraymediumguide ready
- Find First and Last Position of Element in Sorted Arraymediumguide ready
- Single Element in a Sorted Arraymediumguide ready
- Count Occurrences in a Sorted Arraymediumguide ready
- Find Peak Elementmediumguide ready
- Find a Fixed Point (Value equal to index) in a given arraymediumguide ready
- Bishu and Soldiersmediumguide ready
- Missing Number in APmediumguide ready