Sub topic 13
Binary Search over an Answer Range
This chapter assumes you already know the iterative binary search from earlier chapters. It also assumes you can read the half-open lo < hi loop used for lower bound. Up to now, binary search has looked for a value inside a sorted array. Here you search a range of possible answers instead. No array needs to exist.
The Key Idea: A Monotonic Predicate
A predicate is a function that returns true or false. A predicate is monotonic over a range when its results never switch back. For example, it is false up to some point and true from then on. Or it is true for a prefix of the range and false after it.
When that holds, the range behaves like a sorted array of booleans. The answer is the boundary where the result flips, and binary search finds that boundary in O(log R) checks, where R is the size of the range.
You need three things to use this technique:
- A range
[lo, hi]that is sure to contain the answer. - A predicate you can evaluate for any candidate.
- Proof that the predicate is monotonic over that range.
Example: Integer Square Root
To find the largest integer whose square is at most n, test the predicate mid * mid <= n. It is true for 0, 1, ..., up to the answer, and false for every larger value.
def isqrt(n):
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * mid <= n:
lo = mid
else:
hi = mid - 1
return lo
print(isqrt(0)) # 0
print(isqrt(8)) # 2
print(isqrt(16)) # 4The invariant is that lo always satisfies the predicate and the answer lies in [lo, hi]. When the predicate is true, mid might be the answer, so the code keeps it with lo = mid. When it is false, mid is ruled out, so the code sets hi = mid - 1.
Example: Smallest Capacity That Works
Searching for a minimum is the mirror image. Suppose packages with the given weights must ship in order within days days, and each day's load cannot exceed a fixed capacity. Any capacity at least as large as a working capacity also works, so the predicate "this capacity ships everything in time" goes false, then true.
def days_needed(weights, cap):
days, load = 1, 0
for w in weights:
if load + w > cap:
days += 1
load = 0
load += w
return days
def min_capacity(weights, days):
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if days_needed(weights, mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
print(min_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) # 15The bounds come from the problem itself. A capacity below max(weights) can never carry the heaviest package. A capacity of sum(weights) ships everything in one day. This loop has the same shape as lower bound: it returns the first candidate where the predicate is true.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Predicate not monotonic | Wrong answers with no clear pattern | Prove that true implies true for all larger (or smaller) candidates |
| Range excludes the answer | Returns `lo` or `hi` when it should not | Choose bounds that are guaranteed to contain the answer |
| `lo = mid` with round-down midpoint | Infinite loop | Use `(lo + hi + 1) // 2` |
| Overflow in `mid * mid` (Java, C++) | Negative or wrapped products | Use `long`, or compare `mid <= n / mid` |
The total cost is O(log R) evaluations of the predicate multiplied by the cost of one evaluation. In the capacity example, each evaluation is O(n), so the whole search takes O(n log(sum − max)).
Exercise
In isqrt, what happens for n = 8 if you change the midpoint to (lo + hi) // 2 and change nothing else?
Show answer
The search narrows to lo = 2 and hi = 3. Then mid = 2, and 2 * 2 <= 8 is true, so lo = mid = 2. The range never shrinks, so the loop runs forever. The true branch assigns lo = mid, so the midpoint has to round up.
Exercise
Write a function that returns the smallest integer x >= 0 with x * x >= n. Which loop shape should it use?
Show answer
The predicate x x >= n is false and then true, so use the lower-bound shape: lo, hi = 0, n; while lo < hi: mid = (lo + hi) // 2; if mid mid >= n: hi = mid, else: lo = mid + 1; return lo. Rounding down is safe here because the true branch assigns hi = mid, not lo = mid.