Sub topic 11
Lower Bound, Upper Bound, and Duplicates
This chapter assumes you already know the iterative binary search from earlier chapters and can reason about its loop invariant. It also assumes you are comfortable with zero-based indexing and half-open ranges such as [lo, hi).
Classic binary search answers one question: is the target here, and if so, where? When the list contains duplicates, the index it returns can be any of the matching positions. It also tells you nothing useful when the target is missing. Two variants solve both problems.
Two Questions Instead of One
The lower bound of a target is the first index whose element is not less than the target, meaning a[i] >= target. The upper bound is the first index whose element is greater than the target, meaning a[i] > target.
Both always return a valid position from 0 to len(a), even when the target is absent. That position is the insertion point, the place where the target could go while keeping the list sorted.
| List `[1, 3, 3, 3, 7]` | lower bound | upper bound |
|---|---|---|
| target 3 | 1 | 4 |
| target 4 | 4 | 4 |
| target 0 | 0 | 0 |
| target 8 | 5 | 5 |
The matching elements occupy the half-open range [lower, upper). So the number of copies of the target is upper - lower. When that difference is zero, the target is not in the list.
The Half-Open Invariant
Both functions keep the search range as [lo, hi) and keep this invariant true on every step:
- Every index before
loholds an element that fails the condition (it is too small). - Every index at or after
hiholds an element that meets the condition.
The loop runs while lo < hi. When the range is empty, lo == hi, and that index is the boundary between the elements that fail the condition and the elements that meet it.
Notice that hi = mid, not mid - 1. The element at mid might be the answer, so it has to stay inside the range. Writing mid - 1 here is the most common bug in this variant.
Implementing Both Bounds
The two functions differ by a single comparison operator.
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 count(a, target):
return upper_bound(a, target) - lower_bound(a, target)
a = [1, 3, 3, 3, 7]
print(lower_bound(a, 3)) # 1
print(upper_bound(a, 3)) # 4
print(count(a, 3)) # 3
print(count(a, 4)) # 0
print(lower_bound(a, 8)) # 5The loop always ends. Because mid is rounded down, mid < hi holds, so both branches make the range strictly smaller. Each call costs O(log n), the same as ordinary binary search.
Common Uses
- Membership test: find
i = lower_bound(a, t), then checki < len(a) and a[i] == t. Check the index before you reada[i], becauseican equallen(a). - First and last occurrence: the first copy is at
lower_bound, and the last copy is atupper_bound - 1. Both are valid only when the count is positive. - Range counting: the number of elements in
[x, y]isupper_bound(a, y) - lower_bound(a, x). - Sorted insertion: inserting at
upper_boundplaces a new item after its equal elements, which keeps equal items in the order they arrived.
Exercise
For a = [2, 4, 4, 4, 4, 9], what do lowerbound(a, 4) and upperbound(a, 4) return, and how many elements fall in the closed range [3, 5]?
Show answer
lowerbound returns 1 and upperbound returns 5, so there are 5 - 1 = 4 copies of 4. The count for [3, 5] is upperbound(a, 5) - lowerbound(a, 3) = 5 - 1 = 4.
Exercise
A teammate writes lower_bound with hi = mid - 1 in the else branch and keeps while lo < hi. What goes wrong on a = [1, 3] with target 3?
Show answer
lo=0, hi=2, mid=1. a[1] is not less than 3, so hi becomes 0. The loop exits and returns 0, which is wrong (the correct answer is 1). Setting hi = mid - 1 throws away the element at mid, which could be the answer, and that breaks the invariant that every index at or after hi meets the condition.