Binary search without off-by-one errors: the invariant
1 Why binary search goes wrong
A sorted array holds 10⁵ values, and a problem asks 10⁵ questions about it. Where does the first 7 sit? How many 7s are there? Where would an 8 go? Reading the array from the left for each question takes around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
Binary search answers each question in about 17 steps. It looks at a middle value and throws away the half that cannot hold the answer, again and again. The idea fits in one sentence, but the code is famous for small mistakes:
- Does the loop run while
l < ror whilel <= r? - Does
rbecomemidormid - 1? - Does the function return
l,ror −1?
A wrong choice gives a wrong index on some inputs, or a loop that never ends. We can make those choices once. We turn every question into the same question, write one loop for it, and keep one sentence true at every step. That sentence is the invariant. Each line of the loop follows from it, so nothing is left to guess.
Our array for the whole lesson has a run of 7s:
2 Every question is a row of no and yes
We ask every value the same question: is nums[i] >= 7? The array is sorted, so the answers cannot jump around. Once a value is 7 or more, every value after it is too. The answers read no, no, and then yes to the end:
The place where no turns into yes is the boundary. The first yes, at index 2, is the first 7. Most binary search questions ask for the first yes, with a different question put to each value.
The faded box at index 8 is not in the array. We pretend it says yes, so a first yes always exists. If every real value says no, the answer is 8, the length of the array. For "where would 20 go", 8 is right: at the end.
The sorted order gives us one more thing. One answer tells us about a whole half:
- mid says yes. Every index after it says yes too. The first yes is at mid or to its left.
- mid says no. Every index before it says no too. The first yes is to its right.
3 The invariant: no before l, yes from r
We keep two indexes, l and r, and one rule about them:
The indexes from l up to r - 1 are the ones we have not asked yet. The loop has three parts, and the rule decides each one:
- Start.
l = 0andr = n. Nothing sits before index 0, and from n on there is only the pretend yes. So the rule holds before we ask anything. - Each step. Ask
mid, a middle index fromltor - 1. On yes,r = mid, because mid and everything after it say yes. On no,l = mid + 1, because mid and everything before it say no. The rule still holds, and the unknown part is smaller. - Stop. When
lequalsr, nothing is unknown. Everything beforelsays no, and everything fromlon says yes. Solis the first yes.
Here is the search for the first value ≥ 7. Faded values in nums are ruled out:
The same run as a trace table:
| step | l | r | mid | nums[mid] | ≥ 7? | move |
|---|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 7 | yes | r = 4 |
| 2 | 0 | 4 | 2 | 7 | yes | r = 2 |
| 3 | 0 | 2 | 1 | 4 | no | l = 2 |
| end | 2 | 2 | return 2 |
The loop asked three of the eight values. It never checked whether nums[mid] equals 7. When l meets r, the rule alone says where the first 7 is.
4 The code
The loop is the rule written in code. r starts at n, not n - 1. It marks the first index known to say yes, and at the start that is the pretend box.
C++
The division rounds down here. (r - l) / 2 divides two non-negative ints, so it drops the fraction, and mid never reaches r.
The division rounds down here. (r - l) / 2 divides two non-negative ints, so it drops the fraction, and mid never reaches r.
Use //, not /. / gives a float such as 3.5, and a list cannot be indexed with a float.
Use Math.floor. / keeps the fraction, so (r - l) / 2 can be 3.5, and nums[3.5] is undefined.
The division rounds down here. (r-l)/2 divides two non-negative ints, so it drops the fraction, and mid never reaches r.
No index goes below 0. l, r and mid are usize, which cannot hold −1. This loop never subtracts 1 from an index, so it never underflows.
The division rounds down here. (r - l) / 2 divides two non-negative ints, so it drops the fraction, and mid never reaches r.
On our array, every tab returns 2 for target 7, 5 for target 8 and 8 for target 20. On an empty array it returns 0 without reading anything.
5 Where mid sits, and why the loop ends
The middle is l + (r - l) / 2, not (l + r) / 2. In an array, l + r stays below about 2 × 10⁵, so either works. But the next lesson runs the same loop over numbers instead of indexes, and there l and r can both be near 2 × 10⁹. Their sum passes the 32-bit limit of about 2.1 × 10⁹ and turns negative. r - l never grows past r, so the first form stays in range.
The loop ends because the unknown part shrinks at every step. The division rounds down, so mid is always below r. Then r = mid makes the range smaller, and so does l = mid + 1.
A common slip is l = mid, written because "mid might be the answer". But mid said no, so it cannot be the first yes. On the two values [4, 7] with target 7, the loop gets stuck:
| l | r | mid | nums[mid] ≥ 7? | move |
|---|---|---|---|---|
| 0 | 2 | 1 | yes | r = 1 |
| 0 | 1 | 0 | no | l = mid = 0 |
| 0 | 1 | 0 | no | l = mid = 0 |
From the second row on, nothing changes. With two indexes left, the rounded-down mid is l itself, and l = mid does not move it. The loop runs forever, and the program gets TLE.
Other templates search for the last no and move l = mid. Those must round mid up instead. Each template's rounding fits its own moves, and most binary search bugs come from mixing parts of two templates. We use one template, so we never need to round up.
6 One loop, many questions
Only the question put to nums[mid] changes. The two that matter most are the lower bound, the first value ≥ x, and the upper bound, the first value greater than x. For x = 7, their two rows of answers have boundaries three places apart, and the 7s sit between them:
The upper bound is the same loop with > in place of >=. At mid 4, the value 7 is not more than 7, so l = 5. Mid 6 and then mid 5 say yes, and the loop stops at 5.
Most questions about a value in a sorted array come from these two numbers:
| Question | From the bounds | x = 7 | x = 8 |
|---|---|---|---|
| Insert position of x | lower | 2 | 5 |
| Is x there | lower < n and nums[lower] == x | yes | no |
| First index of x | lower, if x is there | 2 | −1 |
| Last index of x | upper − 1, if x is there | 4 | −1 |
| How many x | upper − lower | 3 | 0 |
| Smallest value ≥ x | nums[lower], if lower < n | 7 | 9 |
| Largest value ≤ x | nums[upper - 1], if upper > 0 | 7 | 7 |
Most languages have the two bounds built in. Some only have a plain search, which returns any copy of x rather than the first one:
C++
lower_bound and upper_bound. Each returns an iterator, and subtracting nums.begin() turns it into an index: 2 and 5 for 7. partition_point takes any condition, but the other way round: it returns the first index where the condition is false, so the condition describes the no part.
No lower bound built in. Arrays.binarySearch(nums, 7) returns 3 here: a 7, but not the first. When x is missing, it returns −(insert position) − 1, so for 8 it returns −6. Write the loop above for the bounds.
bisect_left and bisect_right. These two from the bisect module are the lower and upper bounds: 2 and 5 for 7. Since Python 3.10 they also take a key function.
No built-in binary search. Write the loop above, and change >= to > for the upper bound.
sort.Search(n, f) returns the first index where f(i) is true, exactly our loop. sort.SearchInts(nums, 7) is the lower bound, 2. slices.BinarySearch(nums, 7) returns the lower bound and whether 7 is there.
partition_point returns the first index where its condition is false, so the condition describes the no part. nums.partition_point(|&v| v < 7) is 2, and |&v| v <= 7 gives 5. nums.binary_search(&7) returns Ok(4) here: a 7, but not the first.
No lower bound built in. Array.BinarySearch(nums, 7) returns 3 here: a 7, but not the first. When x is missing, it returns the insert position with every bit flipped, so ~Array.BinarySearch(nums, 8) is 5. Write the loop above for the bounds.
7 Cost
Each step halves the unknown part. Our 8 indexes needed three questions. At n = 10⁵, it takes about 17, and at n = 10⁹ about 30, because 2³⁰ is about 10⁹. So binary search takes O(log n) time. It keeps two indexes and nothing else, so the extra space is O(1).
For the 10⁵ questions from the start, that is about 2 × 10⁶ steps instead of 10¹⁰:
The array must be sorted first. An unsorted array costs O(n log n) to sort once, and then each question costs O(log n). For a single question, one O(n) pass is cheaper than sorting.
8 Mistakes, and when to use it
- Stopping at the first match. A search that returns as soon as
nums[mid] == xfinds a 7, not the first 7. The usual form, withr = n - 1, looks at index 3 first on our array and returns 3. The bounds never stop early, so they always land on the boundary. - Reading
nums[l]without checkingl < n. For x = 20 the lower bound is 8, past the end. Readingnums[8]gives a Runtime Error, or a garbage value in C++. while (l <= r)withr = n. This mixes two templates. With x = 7,landrmeet at 2, mid is 2, andr = midchanges nothing, so the loop never ends. With x = 20, mid reaches 8 and reads past the end.l = mid. On[4, 7]with target 7, the loop never ends, as section 5 showed.- Answers that flip more than once. The unsorted
[5, 9, 1, 7]gives no, yes, no, yes for ≥ 7. The loop asks index 2, hears no, and moveslpast it, which rules out index 1 too. It returns 3, but the first value ≥ 7 is at index 1.
The sign is a question about the first position where a condition becomes true. Write the condition as a question about one index, and check that its answers go from no to yes and never back:
- A sorted array and a value. Pick
>=or>, and read the answer off the table in section 6. - An array that is not sorted. Binary search can still work. The rotated array and the mountain later in this topic are not sorted, but each has a question whose answers flip only once. Finding that question is the real work.
- No array at all. The next lesson runs the same loop over possible answers instead of indexes.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.