Sub topic 8
Getting the Boundaries Right with Loop Invariants
Binary search fits in about a dozen lines, and most bugs in it come from a few characters: < against <=, mid against mid + 1, len(a) against len(a) - 1. This chapter replaces trial and error with a precise rule. You state what the range [lo, hi] means, then check every line against that meaning.
This chapter assumes you have read the previous chapters on iterative binary search and its O(log n) cost. It also assumes you can read Python, use zero-based indexing, and run a script. Midpoint overflow, recursion, and the lower-bound and upper-bound variants come in later chapters. Here we stay with the exact-match search.
What a Loop Invariant Is
A loop invariant is a statement about the program's variables that is true every time the loop condition is about to be checked. To trust an invariant, you prove three things:
- Initialization. The statement is true before the first iteration.
- Maintenance. If the statement is true at the start of an iteration, it is still true at the start of the next one.
- Termination. When the loop stops, the invariant plus the reason the loop stopped tell you the answer is correct.
For binary search you also need a fourth property, progress: every iteration makes the range strictly smaller. Without progress the loop can run forever even when the invariant holds.
The Invariant for the Inclusive Range
The binary search from the earlier chapter uses an inclusive range: both lo and hi are indices the target might still be at. Its invariant is:
- Every index less than
loholds a value less thantarget. - Every index greater than
hiholds a value greater thantarget.
Put another way, if target is in the list, it sits at an index inside [lo, hi].
Here is each line of the algorithm checked against that statement.
| Line | What it must do | Why it is correct |
|---|---|---|
| `lo, hi = 0, len(a) - 1` | Make the invariant true at the start | No index is below 0 or above `len(a) - 1`, so both claims hold trivially |
| `while lo <= hi` | Continue while candidates remain | `[lo, hi]` holds `hi - lo + 1` indices, which is at least one exactly when `lo <= hi` |
| `mid = (lo + hi) // 2` | Choose a candidate inside the range | When `lo <= hi`, `lo <= mid <= hi` |
| `lo = mid + 1` | Discard `mid` and everything left of it | `a[mid] < target` and the list is sorted, so every index up to `mid` is too small |
| `hi = mid - 1` | Discard `mid` and everything right of it | `a[mid] > target`, so every index from `mid` onward is too large |
| `return -1` after the loop | Report absence | `lo > hi` means no candidates remain, and the invariant says the target is not outside the range |
Progress holds because mid is inside [lo, hi] and both updates move a boundary past mid. The range loses at least one index per iteration.
Common Boundary Bugs and Which Rule They Break
Each common bug breaks one of the four properties. Once you know which property a change breaks, you know what to fix.
| Bug | Property broken | Symptom |
|---|---|---|
| `while lo < hi` with an inclusive range | Termination | A one-element range is never examined, so `[5]` searched for `5` returns -1 |
| `lo = mid` instead of `lo = mid + 1` | Progress | When `hi = lo + 1`, `mid == lo` and the range never shrinks |
| `hi = mid` with an inclusive range | Progress | When `lo == hi`, `mid == hi` and the loop repeats forever |
| `hi = len(a)` with `while lo <= hi` | Initialization | `hi` is not a valid index, and `a[mid]` can raise `IndexError` |
| `lo = mid - 1` or `hi = mid + 1` | Maintenance and progress | Discarded indices come back and the range can grow |
The lo = mid bug is easy to reproduce. The function below caps its iterations so that it returns a message instead of hanging.
def stuck_search(a, target, max_steps=20):
lo, hi = 0, len(a) - 1
steps = 0
while lo <= hi:
steps += 1
if steps > max_steps:
return f"stuck at lo={lo}, hi={hi}"
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid # bug: should be mid + 1
else:
hi = mid - 1
return -1
print(stuck_search([1, 3], 5)) # stuck at lo=0, hi=1With lo = 0 and hi = 1, floor division gives mid = 0. Since a[0] < 5, the bug sets lo back to 0. The state never changes. The invariant still holds here, which shows why progress has to be checked separately.
The Half-Open Convention
Many programmers and standard libraries use a half-open range [lo, hi) instead. In that convention, lo is a candidate and hi is one past the last candidate. The invariant becomes:
- Every index less than
loholds a value less thantarget. - Every index greater than or equal to
hiholds a value greater thantarget.
Every line changes to match:
def binary_search_half_open(a, target):
lo, hi = 0, len(a) # hi is one past the last candidate
while lo < hi: # range [lo, hi) is non-empty
mid = (lo + hi) // 2 # lo <= mid < hi
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid # mid is excluded because hi is exclusive
return -1
print(binary_search_half_open([1, 3, 5, 7, 9, 11], 7)) # 3
print(binary_search_half_open([1, 3, 5, 7, 9, 11], 4)) # -1
print(binary_search_half_open([], 4)) # -1In this convention hi = mid is correct. Because lo < hi, floor division gives mid < hi, so setting hi = mid always shrinks the range. The same line was a bug in the inclusive version. Whether a line is correct depends on which convention you chose.
| Aspect | Inclusive `[lo, hi]` | Half-open `[lo, hi)` |
|---|---|---|
| Initial `hi` | `len(a) - 1` | `len(a)` |
| Loop condition | `lo <= hi` | `lo < hi` |
| Range size | `hi - lo + 1` | `hi - lo` |
| Discard right half | `hi = mid - 1` | `hi = mid` |
| Discard left half | `lo = mid + 1` | `lo = mid + 1` |
| Empty list | `hi = -1`, loop never runs | `hi = 0`, loop never runs |
Debugging with Executable Invariants
You can turn the invariant into assertions. If a change breaks it, the assertion fails in the iteration where the problem starts. It does not wait for a wrong answer at the end. The assertions scan the list, so they cost O(n) per iteration. Use them only while testing.
def binary_search_checked(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
# Invariant: indices < lo hold values < target,
# indices > hi hold values > target.
assert all(a[i] < target for i in range(lo)), "left side broken"
assert all(a[i] > target for i in range(hi + 1, len(a))), "right side broken"
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Add a randomized test that compares the result with what must be true. With duplicates, binary search can return any index that holds the target. The test therefore checks the returned index's value and does not compare against one fixed index.
import random
def binary_search_checked(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
assert all(a[i] < target for i in range(lo)), "left side broken"
assert all(a[i] > target for i in range(hi + 1, len(a))), "right side broken"
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def buggy_search(a, target):
lo, hi = 0, len(a) - 1
while lo < hi: # bug: skips one-element ranges
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def check(search, trials=10_000):
random.seed(1)
for _ in range(trials):
n = random.randint(0, 8)
a = sorted(random.randint(0, 10) for _ in range(n))
target = random.randint(-1, 11)
r = search(a, target)
if target in a:
assert 0 <= r < len(a) and a[r] == target, (a, target, r)
else:
assert r == -1, (a, target, r)
print(search.__name__, "passed")
check(binary_search_checked)
try:
check(buggy_search)
except AssertionError as e:
print("buggy_search failed on (list, target, result):", e)Small lists (up to 8 elements) and a small value range (0 to 10) are deliberate choices. They produce many duplicates, empty lists, one-element lists, and targets below, above, and between the stored values. Those are the inputs where boundary bugs show up. For a manual check, test at least these cases: an empty list, one element present, one element absent, the first index, the last index, a value smaller than all elements, a value larger than all elements, and a missing value that falls between two elements.
Exercise
A colleague writes lo, hi = 0, len(a) and keeps while lo <= hi, lo = mid + 1, and hi = mid - 1. Which invariant property does this break, and what happens for a = [1, 3] and target = 5?
Show answer
It breaks initialization. The inclusive invariant needs hi to be a valid candidate index, but len(a) is one past the end. Trace: lo=0, hi=2, mid=1, and a[1]=3 < 5, so lo=2. Then lo=2, hi=2, mid=2, and reading a[2] raises IndexError.
Exercise
In the inclusive version, why does replacing hi = mid - 1 with hi = mid risk an infinite loop? Give a concrete input.
Show answer
It breaks progress. When lo == hi, mid equals hi, so hi = mid leaves the range unchanged. For a = [5] and target = 3: lo=0, hi=0, mid=0, and a[0]=5 > 3, so hi stays 0. The state repeats forever.
Exercise
State the loop invariant for binary_search_half_open. Explain why return -1 after the loop is correct.
Show answer
Every index less than lo holds a value less than the target, and every index greater than or equal to hi holds a value greater than the target. The loop exits when lo >= hi, and because each update shrinks the range by at least one, it exits exactly when lo == hi. Then every index is either below lo or at least hi, so no index can hold the target, and -1 is correct.