Off-by-one traps
After this: Name the three details that make binary search hard to write.
On this page · 7 sections · 3 checks
The loop from the last lesson is only a few lines long, but it is hard to get right. Binary search was first described in 1946, and more than ten years passed before anyone published a version that worked for every array size. Jon Bentley gave the problem to professional programmers, with a couple of hours to write it, and most of their programs had a bug. Java's own Arrays.binarySearch had a bug for about nine years.
The bugs are in three small details. The first two are , where a number in the code is wrong by exactly one. The third is about very large numbers. We follow one small search for each trap.
Trap 1: where hi starts
Our loop treats lo and hi as real cells, both included. A range like this is called a . So hi must start at the last index, n - 1: five cells have indexes 0 to 4.
The trap is to start hi at n and keep everything else the same. Here is [10, 20, 30, 40, 50] with hi starting at 5, searching for 60.
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 30 | Too small, so lo becomes 3 |
| 2 | 3 | 5 | 4 | 50 | Too small, so lo becomes 5 |
| 3 | 5 | 5 | 5 | no such cell | Index 5 does not exist, so the program stops with an error |
The bug stays hidden for most targets: with the same wrong hi, a search for 20 finds it, and a search for 45 correctly says it is missing. Only a target bigger than every value pushes lo up to n.
def search_wrong_hi(nums, target): lo, hi = 0, len(nums) # the trap: hi is one past the last cell while lo <= hi: # ... and the loop still treats hi as a cell mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(search_wrong_hi(nums, 23)) # 5: the bug hides for most targetsprint(search_wrong_hi(nums, 100)) # IndexError: list index out of rangestatic int searchWrongHi(int[] nums, int target) { int lo = 0, hi = nums.length; // the trap: hi is one past the last cell while (lo <= hi) { // ... and the loop still treats hi as a cell int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1;}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(searchWrongHi(nums, 23)); // 5: the bug hides for most targetsSystem.out.println(searchWrongHi(nums, 100)); // ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10The two highlighted lines disagree. The first says that hi is one past the last cell. The second, lo <= hi, says that hi is a real cell.
Trap 2: keeping mid
After a probe, the cell at mid is not the target, so it must leave the range. The trap is to write lo = mid, because then the range can stop shrinking. Here is the smallest case: [10, 20], searching for 20.
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 10 | Too small, so lo = mid, and lo stays 0 |
| 2 | 0 | 1 | 0 | 10 | Exactly the same as probe 1, and this never ends |
With two cells left, mid is the left cell, so lo = mid sets lo to the place where it already is. In the same way, hi = mid gets stuck when one cell is left and it is too big.
Normally this next loop would run forever, so we added a limit of 20 probes to let the demo stop.
def search_keeping_mid(nums, target): lo, hi = 0, len(nums) - 1 probes = 0 while lo <= hi and probes < 20: # the cap is only here so that the demo stops mid = (lo + hi) // 2 probes += 1 if nums[mid] == target: return f"found at {mid}" if nums[mid] < target: lo = mid # the trap: mid is kept, so the range can stop shrinking else: hi = mid - 1 return f"gave up after {probes} probes with lo = {lo}, hi = {hi}"
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(search_keeping_mid(nums, 56))print(search_keeping_mid(nums, 7))found at 7 gave up after 20 probes with lo = 1, hi = 1
static String searchKeepingMid(int[] nums, int target) { int lo = 0, hi = nums.length - 1; int probes = 0; while (lo <= hi && probes < 20) { // the cap is only here so that the demo stops int mid = lo + (hi - lo) / 2; probes++; if (nums[mid] == target) return "found at " + mid; if (nums[mid] < target) lo = mid; // the trap: mid is kept, so the range can stop shrinking else hi = mid - 1; } return "gave up after " + probes + " probes with lo = " + lo + ", hi = " + hi;}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(searchKeepingMid(nums, 56));System.out.println(searchKeepingMid(nums, 7));found at 7 gave up after 20 probes with lo = 1, hi = 1
The search for 56 works, but the search for 7 only stops because of the limit. A search for 23 also gets stuck, with 16 and 23 as the last two cells.
Watch it happen
Here is the correct loop, on three targets that would expose the first two traps.
- Binary search for 100100 is bigger than every value. lo climbs to 10 and the loop stops because lo > hi. If hi had started at 10 instead of 9, this search would end by reading index 10, which does not exist.
- Binary search for 1
- Binary search for 7
- 02
- 15
- 28
- 312
- 416
- 523
- 638
- 756
- 872
- 991
Run an operation to begin.
Trap 3: the middle of two big numbers
This trap needs a very big array, and a language like Java. The largest value a Java int can hold is 2,147,483,647. When a sum goes past that limit, Java gives no error: the result wraps round to a negative number. This is called .
Suppose lo = 1,500,000,000 and hi = 2,000,000,000. Here is (lo + hi) / 2 in Java.
- The true sum is 3,500,000,000, which is past the limit.
- The sum wraps round to −794,967,296.
- Half of that is −397,483,648, which is not a valid index.
Now the same numbers with lo + (hi - lo) / 2.
hi - lois 500,000,000, which fits.- Half of that is 250,000,000.
- Adding lo gives 1,750,000,000, the correct middle.
lo, hi = 1_500_000_000, 2_000_000_000 # indexes in a row of two billion cellsprint((lo + hi) // 2) # Python integers never overflowprint(lo + (hi - lo) // 2) # the same value, the same way1750000000 1750000000
int lo = 1_500_000_000, hi = 2_000_000_000; // indexes in a row of two billion cellsSystem.out.println((lo + hi) / 2); // lo + hi overflows int: a negative "index"System.out.println(lo + (hi - lo) / 2); // hi - lo cannot overflow: the right answer-397483648 1750000000
Python integers grow without limit, so (lo + hi) // 2 is always right there. In Java the longer form costs almost nothing, and interviewers look for it.
A second way to write the loop
There is a second correct way to write the loop, called a . Here, hi means "one past the end of the range". It starts at n, the loop runs while lo < hi, and the move left is hi = mid.
Take the first trace again in this style. lo goes from 0 to 3 to 5, and then lo equals hi, so the loop stops without reading index 5.
Both ways work. Mixing them is the bug.
| Style | hi starts at | Loop | Go right | Go left |
|---|---|---|---|---|
| Closed, hi is included | n - 1 | while lo <= hi | lo = mid + 1 | hi = mid - 1 |
| Half-open, hi is not included | n | while lo < hi | lo = mid + 1 | hi = mid |
Check yourself
This version starts hi at the length instead of the last index. Searching [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] for 100, what happens?
def search_wrong_hi(nums, target): lo, hi = 0, len(nums) # the trap: hi is one past the last cell while lo <= hi: # ... and the loop still treats hi as a cell mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(search_wrong_hi(nums, 23)) # 5: the bug hides for most targetsprint(search_wrong_hi(nums, 100)) # IndexError: list index out of rangestatic int searchWrongHi(int[] nums, int target) { int lo = 0, hi = nums.length; // the trap: hi is one past the last cell while (lo <= hi) { // ... and the loop still treats hi as a cell int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1;}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(searchWrongHi(nums, 23)); // 5: the bug hides for most targetsSystem.out.println(searchWrongHi(nums, 100)); // ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10Searching the same array for 7 with lo = mid instead of lo = mid + 1, and with no limit on the probes. What happens?
def search_keeping_mid(nums, target): lo, hi = 0, len(nums) - 1 probes = 0 while lo <= hi and probes < 20: # the cap is only here so that the demo stops mid = (lo + hi) // 2 probes += 1 if nums[mid] == target: return f"found at {mid}" if nums[mid] < target: lo = mid # the trap: mid is kept, so the range can stop shrinking else: hi = mid - 1 return f"gave up after {probes} probes with lo = {lo}, hi = {hi}"
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(search_keeping_mid(nums, 56))print(search_keeping_mid(nums, 7))static String searchKeepingMid(int[] nums, int target) { int lo = 0, hi = nums.length - 1; int probes = 0; while (lo <= hi && probes < 20) { // the cap is only here so that the demo stops int mid = lo + (hi - lo) / 2; probes++; if (nums[mid] == target) return "found at " + mid; if (nums[mid] < target) lo = mid; // the trap: mid is kept, so the range can stop shrinking else hi = mid - 1; } return "gave up after " + probes + " probes with lo = " + lo + ", hi = " + hi;}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(searchKeepingMid(nums, 56));System.out.println(searchKeepingMid(nums, 7));Why do Java programmers write mid = lo + (hi − lo) / 2 rather than (lo + hi) / 2?
Connect
- Start hi at n − 1 for a closed range or at n for a half-open one, and never mix the two.
- Move lo to mid + 1 and hi to mid − 1, because the cell at mid has been ruled out.
- Write mid = lo + (hi − lo) / 2 in Java, and say why (lo + hi) / 2 can overflow.