Sub topic 13
Binary Search over an Answer Range
So far, binary search has looked for a value stored in a sorted array. This chapter uses the same halving idea where no array exists. You search over a range of possible answers, and the "sorted data" is a yes/no question whose answers flip exactly once as the candidate grows.
This chapter assumes you already know the following:
- Iterative binary search with inclusive and half-open ranges
- Lower-bound search, meaning the first index where a condition becomes true
- Loop invariants as a way to check boundary updates
- Big-O notation for loops and nested work
The Core Idea: A Monotonic Predicate
A predicate is a function that returns True or False. A predicate is monotonic over a range of integers if, once it becomes true, it stays true for every larger value. The predicate's outputs across the range then look like this:
x: 0 1 2 3 4 5 6 7
pred(x): F F F F T T T TThat pattern is sorted, with every False before every True. Lower-bound search already finds the first position where a sorted sequence meets a condition, so it can also find the first True here. The only change is that you compute pred(mid) on demand instead of reading a[mid] from memory.
Many optimization problems take this form. "What is the smallest capacity that works?" becomes "Is capacity c enough?", and the answer to that question flips from no to yes at the value you want.
The mirror image is also common. A predicate can be true for a prefix and false afterward (T T T F F). In that case you want the last true value, for example "the largest x with x * x <= n".
A Reusable "First True" Template
The function below finds the smallest x in [lo, hi] for which pred(x) is true. It converts the range to half-open form [lo, hi + 1) so that "no value works" has its own return value.
def first_true(lo, hi, pred):
"""Smallest x in [lo, hi] with pred(x) True, or hi + 1 if none."""
hi += 1 # search the half-open range [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid # mid works; the answer is mid or smaller
else:
lo = mid + 1 # mid fails; the answer is larger
return lo
print(first_true(0, 7, lambda x: x >= 4)) # 4
print(first_true(0, 7, lambda x: x >= 99)) # 8 (none in range)The invariant matches the one in lower bound. Everything below lo is known to be false, and everything at or above hi is known to be true or lies outside the range. Each step shrinks [lo, hi), and the loop stops when the unknown region is empty. At that point lo is the boundary.
Worked Example: Minimum Shipping Capacity
Here is the problem. Packages with weights weights must ship in the given order. Each day you load packages onto a ship until the next one would go over the capacity, and then that package waits for the next day. What is the smallest capacity that ships everything within days days?
Searching the weights array does not solve this. Instead, ask: given capacity c, can we finish in days days? Greedy loading answers that in one pass. A larger capacity never needs more days, so the predicate is monotonic.
Choosing the bounds takes some care:
- Lower bound:
max(weights). With less capacity, the heaviest package can never be loaded. - Upper bound:
sum(weights). With this capacity everything ships in one day, so the predicate is guaranteed true there.
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 first_true(lo, hi, pred):
hi += 1
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
def min_capacity(weights, days):
return first_true(
max(weights),
sum(weights),
lambda cap: days_needed(weights, cap) <= days,
)
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(min_capacity(weights, 5)) # 15
print(min_capacity(weights, 1)) # 55
print(min_capacity(weights, 10)) # 10With capacity 14, the loads are [1..5]=15? No, 15 is over 14, so the first day takes 1+2+3+4=10, followed by 5+6=11, 7, 8, 9, and 10. That is six days, which is too many. With capacity 15 the loads are [1,2,3,4,5], [6,7], [8], [9], [10], which is five days. So 15 is the first True.
Cost
The search makes about log2(sum - max + 1) calls to the predicate, and each call takes O(n). The total is O(n · log S), where S is the width of the answer range. Trying every capacity in order would cost O(n · S). That is a linear search over answers, and it gets slow when S is in the millions.
Finding the Last True: Integer Square Root
When the predicate is true first and then false, you want the largest true value. The integer square root of n is the largest x with x * x <= n.
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 here is that the answer always lies in [lo, hi] and lo always satisfies the predicate. The update lo = mid keeps mid as a candidate because it passed the test.
Why mid rounds up
Suppose lo = 2 and hi = 3. Rounding down gives mid = 2. If the predicate is true, lo = mid sets lo to 2 again, nothing changes, and the loop never ends. Rounding up gives mid = 3, so each branch makes progress: either lo becomes 3 or hi becomes 2.
The rule is: if one branch assigns lo = mid, round up; if one branch assigns hi = mid, round down. Choose the rounding so that mid never equals the bound being assigned to.
Trace for isqrt(8):
| lo | hi | mid | mid*mid <= 8? | Update |
|---|---|---|---|---|
| 0 | 8 | 4 | 16, no | hi = 3 |
| 0 | 3 | 2 | 4, yes | lo = 2 |
| 2 | 3 | 3 | 9, no | hi = 2 |
| 2 | 2 | – | loop ends | return 2 |
Real-Valued Answer Ranges
Some answers are real numbers, such as a cube root or a minimum speed. Floating-point bounds never become equal in a useful way, so run a fixed number of iterations instead of looping until lo < hi fails. Each iteration halves the interval, and 100 iterations is far more than double precision can resolve.
def cube_root(y, iterations=100):
"""Cube root of y for y >= 0."""
lo, hi = 0.0, max(1.0, y)
for _ in range(iterations):
mid = (lo + hi) / 2
if mid ** 3 < y:
lo = mid
else:
hi = mid
return hi
print(round(cube_root(2), 6)) # 1.259921
print(round(cube_root(27), 6)) # 3.0Here the bounds are lo = mid and hi = mid, with no +1 or -1, because there is no "next" real number to step to. The upper bound max(1.0, y) matters because for y < 1 the cube root is larger than y.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Wrong answer, with no crash | The predicate is not monotonic | Prove that a larger candidate never turns True back into False |
| Answer is always `lo` or always `hi` | The real answer lies outside the bounds | Choose bounds where the predicate is known to be false and true |
| Infinite loop | `lo = mid` with `mid` rounded down | Round `mid` up when a branch assigns `lo = mid` |
| Returns `hi + 1` unexpectedly | No candidate satisfies the predicate | Check for the sentinel value before using the result |
| Overflow in Java or C | `mid * mid` or `lo + hi` exceeds `int` | Use `long`, `lo + (hi - lo) / 2`, or a division-based check |
Recognizing the Pattern
The technique is worth trying when a problem has these features:
- It asks for a minimum or maximum value, often worded as "smallest X such that..." or "largest X such that...".
- Checking one candidate is easier than finding the best one directly.
- Making the candidate bigger only helps, or only hurts, so the check is monotonic.
- The candidates fall in a known, bounded range.
Typical examples include minimum time, minimum capacity, maximum distance between placed items, and the largest group size that fits a budget.
Exercise
Write max_min_distance(positions, k): given sorted integer positions of stalls and an integer k ≥ 2, place k cows in different stalls so that the smallest distance between any two cows is as large as possible, and return that distance. For positions [1, 2, 4, 8, 9] and k = 3, what does it return, and what predicate makes the search monotonic?
Show answer
The predicate is can_place(d): greedily put the first cow at positions[0], then put each next cow at the first stall at least d past the previous cow, and return True if at least k cows fit. It is true for small d and false for large d, so you want the last True. Search d in [0, positions[-1] - positions[0]] with mid = (lo + hi + 1) // 2, setting lo = mid when can_place(mid) is True and hi = mid - 1 otherwise. For [1, 2, 4, 8, 9] and k = 3 it returns 3 (cows at 1, 4, 8). With d = 4 the greedy places cows at 1 and 8 only.
Exercise
A developer writes the isqrt loop with mid = (lo + hi) // 2 and leaves the rest unchanged. Give an input where it never terminates and explain why.
Show answer
isqrt(1) is one such input. With lo = 0 and hi = 1, mid = 0 and 0 * 0 <= 1 is True, so lo = mid = 0. The state never changes and the loop runs forever. Because one branch assigns lo = mid, mid must be rounded up so that it is always greater than lo.
Exercise
In min_capacity, why is the lower bound max(weights) instead of 1, and would starting at 1 give a wrong answer?
Show answer
Any capacity below the heaviest package can never ship that package. The greedy days_needed would still count days without ever detecting the impossible load, so the predicate could report True for an invalid capacity. Starting at max(weights) keeps every candidate valid. With lo = 1 the result can be wrong, for example for [10] with 1 day, unless the predicate also returns False when cap < max(weights).