Sub topic 11
Lower Bound, Upper Bound, and Duplicates
The binary search from earlier chapters answers one question: "Is the target here, and if so, at which index?" When the list contains duplicates, that answer is weak. In [1, 3, 3, 3, 7], a search for 3 can return index 1, 2, or 3, depending on where the midpoints happen to land. When the target is missing, the classic version returns -1 and throws away the position where the search stopped, which is useful information.
This chapter assumes you can already write the iterative binary search, that you know the inclusive-range [lo, hi] convention and its loop invariant, and that you are comfortable with Python slicing and zero-based indexing.
Two Questions Instead of One
The lower-bound and upper-bound searches replace "where is the target?" with two questions that always have a well-defined answer:
- Lower bound: the first index
iwherea[i] >= target. - Upper bound: the first index
iwherea[i] > target.
If no element qualifies, both return len(a), one past the end. Because the answer is always a valid index in the range 0..len(a), these functions never need a "not found" sentinel value.
A sorted list splits into three consecutive blocks relative to any target: elements less than it, elements equal to it, and elements greater than it. Lower bound points to the start of the equal block, and upper bound points to the start of the greater block. Any of the blocks can be empty.
For a = [1, 3, 3, 3, 7] the two bounds work out as follows:
| target | lower_bound | upper_bound | upper - lower |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 0 | 1 | 1 |
| 3 | 1 | 4 | 3 |
| 4 | 4 | 4 | 0 |
| 7 | 4 | 5 | 1 |
| 8 | 5 | 5 | 0 |
The last column counts how many times the target occurs. When the target is absent, both bounds are equal, and that shared value is the insertion point: the index where you could insert the target and keep the list sorted.
Implementing Lower Bound with a Half-Open Range
These variants are easiest to write with a half-open range [lo, hi). The range includes lo and excludes hi. Here hi starts at len(a) instead of len(a) - 1, because len(a) is a legal answer.
def lower_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
a = [1, 3, 3, 3, 7]
print(lower_bound(a, 3)) # 1
print(lower_bound(a, 4)) # 4
print(lower_bound(a, 8)) # 5The code differs from the classic search in three places:
- The loop condition is
lo < hi, so the loop stops when the range is empty, which happens whenlo == hi. - When
a[mid] >= target, the code setshi = mid, notmid - 1. Indexmidcould be the answer, so it must stay at the excluded edge of the range where it can still be returned. - The loop never checks
a[mid] == targetand never exits early. It keeps narrowing until only the boundary remains.
The Invariant
The loop keeps this invariant true at every step:
- Every element in
a[0:lo]is less thantarget. - Every element in
a[hi:]is greater than or equal totarget.
At the start, lo = 0 and hi = len(a), so both slices are empty and the invariant holds trivially. If a[mid] < target, then because the list is sorted, everything up to and including mid is also less than the target, so lo = mid + 1 keeps the first half of the invariant true. If a[mid] >= target, everything from mid onward is at least the target, so hi = mid keeps the second half true. When the loop ends with lo == hi, nothing is left undecided, and lo is exactly the first index whose element is not less than the target.
Why It Always Terminates
While lo < hi, floor division gives lo <= mid < hi. The branch lo = mid + 1 raises lo by at least one. The branch hi = mid lowers hi by at least one, because mid < hi. Every iteration shrinks the range, so the loop runs at most about log2(n) + 1 times, the same O(log n) bound as the classic search.
Tracing an Example
Here is lower_bound([1, 3, 3, 3, 7], 3) step by step:
| lo | hi | mid | a[mid] | a[mid] < 3? | action |
|---|---|---|---|---|---|
| 0 | 5 | 2 | 3 | no | hi = 2 |
| 0 | 2 | 1 | 3 | no | hi = 1 |
| 0 | 1 | 0 | 1 | yes | lo = 1 |
| 1 | 1 | return 1 |
The search finds a 3 on its very first probe and keeps going anyway. That is intended. Finding a match is not the goal. The goal is the leftmost position where the condition turns true.
Upper Bound: One Character Different
Upper bound uses the same loop. Only the comparison changes from < to <=:
def upper_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
a = [1, 3, 3, 3, 7]
print(upper_bound(a, 3)) # 4
print(upper_bound(a, 4)) # 4
print(upper_bound(a, 7)) # 5The invariant becomes: everything in a[0:lo] is <= target, and everything in a[hi:] is > target.
Both functions answer the same general question: "What is the first index where a condition becomes true?" For lower bound the condition is a[i] >= target. For upper bound it is a[i] > target. In a sorted list each condition is false for a prefix of indices and true for the rest, and that false-then-true shape is the only thing binary search needs. A later chapter applies the same idea to ranges of candidate answers instead of list indices.
Practical Uses
With the two bounds you can build several common operations in a line or two each. Each runs in O(log n).
def lower_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def upper_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
def first_occurrence(a, target):
i = lower_bound(a, target)
if i < len(a) and a[i] == target:
return i
return -1
def last_occurrence(a, target):
j = upper_bound(a, target) - 1
if j >= 0 and a[j] == target:
return j
return -1
def count(a, target):
return upper_bound(a, target) - lower_bound(a, target)
def count_in_range(a, low, high):
"""Number of elements x with low <= x <= high."""
return max(0, upper_bound(a, high) - lower_bound(a, low))
def insert_sorted(a, value):
a.insert(upper_bound(a, value), value)
a = [1, 3, 3, 3, 7]
print(first_occurrence(a, 3)) # 1
print(last_occurrence(a, 3)) # 3
print(first_occurrence(a, 4)) # -1
print(count(a, 3)) # 3
print(count_in_range(a, 2, 7)) # 4
insert_sorted(a, 5)
print(a) # [1, 3, 3, 3, 5, 7]The function count_in_range wraps its result in max(0, ...) because a caller might pass low > high, and the subtraction would then go negative.
Choosing between lower and upper bound for an insertion position matters when equal values carry extra data, such as records sorted by timestamp. Inserting at the upper bound places the new item after existing equal items, which keeps arrival order (a stable insert). Inserting at the lower bound places it before them.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Starting with `hi = len(a) - 1` in the half-open version | Returns `len(a) - 1` when every element is less than the target, so inserts go in the wrong place | Start with `hi = len(a)` |
| Using `while lo <= hi` together with `hi = mid` | Infinite loop once `lo == hi == mid` | Use `lo < hi` with half-open ranges |
| Writing `hi = mid - 1` | Can skip the answer when `a[mid]` is the first match | Keep `mid` in the range with `hi = mid` |
| Treating the returned index as "found" | Reports a match for an absent target, or raises `IndexError` at `len(a)` | Check `i < len(a) and a[i] == target` |
| Mixing `<` and `<=` | Lower bound and upper bound get swapped | Ask which condition must be true at the returned index |
Testing Against a Brute-Force Version
Boundary code is easy to get almost right. A cheap check is to compare it with a slow version that is obviously correct, run on many small random inputs. Small inputs with heavy duplication find off-by-one errors quickly.
import random
def lower_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def upper_bound(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= target:
lo = mid + 1
else:
hi = mid
return lo
def brute_lower(a, target):
return next((i for i, x in enumerate(a) if x >= target), len(a))
def brute_upper(a, target):
return next((i for i, x in enumerate(a) if x > target), len(a))
for _ in range(10000):
a = sorted(random.randint(0, 5) for _ in range(random.randint(0, 8)))
t = random.randint(-1, 6)
assert lower_bound(a, t) == brute_lower(a, t), (a, t)
assert upper_bound(a, t) == brute_upper(a, t), (a, t)
print("all tests passed")The random lists include the empty list, lists where every element is equal, and targets below the minimum and above the maximum. Those are the edge cases where boundary bugs usually show up.
Exercise
For a = [2, 4, 4, 4, 4, 9], what do lowerbound(a, 4), upperbound(a, 4), lowerbound(a, 5), and upperbound(a, 10) return, and how many times does 4 occur?
Show answer
lowerbound(a, 4) = 1, upperbound(a, 4) = 5, lowerbound(a, 5) = 5 (the index of 9, which is also the insertion point for 5), and upperbound(a, 10) = 6, which equals len(a). The count of 4 is 5 - 1 = 4.
Exercise
A colleague changes lower_bound so the loop reads "while lo <= hi" but leaves "hi = mid" as it is. What happens when the function is called on [5] with target 5?
Show answer
The range starts as lo = 0, hi = 1. On the first iteration mid = 0, and a[0] = 5 is not less than 5, so hi = 0. Now lo = 0 and hi = 0, and the loop condition lo <= hi is still true. mid = 0 again, hi stays 0, and the loop runs forever. The half-open convention needs "lo < hi" because the range is empty as soon as lo equals hi.
Exercise
Using only lowerbound and upperbound, write an expression for the number of elements strictly greater than x and strictly less than y in a sorted list a, assuming x < y.
Show answer
lowerbound(a, y) - upperbound(a, x). upperbound(a, x) is the first index with a value greater than x, and lowerbound(a, y) is the first index with a value of at least y. The elements between those two indices are exactly the ones with x < value < y. Wrap the result in max(0, ...) if x < y is not guaranteed.