Mental model
The binary search lesson searched a sorted array: compare the middle element, discard half. What it really relied on was weaker than sortedness. It only needed a yes/no question that is "no" for every position up to some point and "yes" from there on:
candidate: 10 11 12 13 14 15 16 17 … 55
works? no no no no no yes yes yes … yes
↑ the first yes
Such a question is called a monotonic predicate. If you can evaluate it for any candidate, you can binary search for the first "yes" without ever storing the candidates. The candidates are not array elements; they are possible answers, hence the name.
The example: the smallest daily capacity
Packages with weights w[0..n−1] must be delivered in the given order. Each day a truck takes the
next packages in line as long as their total stays within its capacity. What is the smallest
capacity that delivers everything within days days?
Trying capacities one by one works but can be slow: the answer can be as large as the total weight. Binary search on the answer needs three ingredients.
1. A predicate
canShip(capacity): load greedily, starting a new day when the next package does not fit, and
report whether at most days days were needed.
canShip(capacity):
used = 1, load = 0
for w in weights:
if load + w > capacity:
used += 1, load = 0
if used > days: return false # stop early
load += w
return true
Greedy loading is optimal for a fixed capacity: putting a package on today's truck whenever it fits can never force more days later, because any schedule that postpones it leaves at least as much remaining work for the following days. It runs in O(n).
2. Monotonicity
If a capacity c works, every larger capacity works too: run the same day-by-day schedule on a
bigger truck and every day still fits. So the predicate is false … false true … true over
capacities, exactly the shape binary search needs. The lab's Predicate results panel shows each
test; every failing capacity is smaller than every working one.
Monotonicity is the part to prove for every new problem. If it does not hold, binary search returns a confident, wrong answer.
3. Bounds that surely contain the answer
- low = the heaviest package. Below that, one package cannot be loaded at all.
- high = the total weight. Then everything goes on day one, so
canShip(high)is true.
With no packages both are 0 and the answer is 0 without a single test.
The search: the first true
This is the lower-bound loop from the binary search lesson, with values[mid] < target replaced by
"the predicate is false at mid":
low = max(weights), high = sum(weights) # answer in [low, high]
while low < high:
mid = low + (high - low) / 2
if canShip(mid): high = mid # mid works: the first true is mid or earlier
else: low = mid + 1 # mid fails: so does everything below it
return low
Invariant: the first working capacity is in [low, high]. It holds initially by the choice of
bounds; high = mid keeps it because mid itself works; low = mid + 1 keeps it because mid
and everything below fail. When low == high, that single candidate is the answer. Because
mid < high always, every iteration shrinks the range, so the loop terminates.
On the lab's first preset (weights 1 to 10, five days) the candidates are 10…55. The tests run 32 ✓, 21 ✓, 15 ✓, 12 ✗, 14 ✗, and the range closes on 15: five predicate calls for 46 candidates. The Large weights preset has 4,161 candidates and needs 12.
Complexity
With n packages and R = sum − max + 1 candidate capacities:
| Approach | Predicate calls | Time | Extra space |
|---|---|---|---|
| Linear scan upward from max | up to R | O(n · R) | O(1) |
| Binary search on the answer | at most ⌈log₂ R⌉ | O(n · log R) | O(1) |
R can be enormous (weights up to 10⁹ make it about 10⁹ · n), yet log₂ R stays small: about 30
plus log₂ n. The Package checks metric counts the real work inside canShip; the early exit
when a day too many is needed makes failing tests cheaper than successful ones.
Recognising the pattern
Look for these signals:
- the question asks for the minimum (or maximum) value of something, such as a capacity, a speed, a time, a distance or a size;
- checking whether a given value is good enough is much easier than computing the best value directly;
- making the value larger (or smaller) can only turn a "no" into a "yes", never back.
The same skeleton answers "the smallest speed to finish in h hours", "the largest minimum distance between k placed items", "the smallest maximum part sum when splitting into k parts" (the capacity problem in disguise) and "the first day on which something has happened". For a maximum, search for the last true instead: flip the roles of the branches, or search for the first false and subtract one.
A boolean array works too: the problem bank's
Find the first broken build asks for
the first true in a list of build results, the same lower bound over indices. Over sorted values,
Where does a value start and end?
uses the predicates value ≥ target and value > target.
Language notes
Overflow. The upper bound is a sum of weights, which can exceed 2³¹ − 1 even when every
weight fits in an int. The listings keep low, high, mid, the capacity and the daily load in
long (C#, Java) or std::int64_t (C++), and compute mid = low + (high − low) / 2, which never
exceeds high. In C++, signed overflow would be undefined behaviour, not just a wrong number. The
C#, Java and C++ tests use three weights of int.MaxValue / INT_MAX, so the answer itself is
beyond 32 bits. Python integers have arbitrary precision, so its listing keeps the simpler
(low + high) // 2.
Library searches over a predicate.
| Language | First true over a range of numbers | Notes |
|---|---|---|
| C# | no built-in for a predicate | Array.BinarySearch needs a materialised, sorted array |
| Python 3.10+ | low + bisect.bisect_left(range(low, high + 1), True, key=pred) |
range is indexable without being stored; key is applied to the candidates, and False < True |
| Java | no built-in for a predicate | Arrays.binarySearch / Collections.binarySearch need a stored array or list |
| C++20 | *std::ranges::partition_point(std::views::iota(low, high + 1), [&](auto c) { return !can_ship(c); }) |
partition_point returns the first element for which the predicate is false, so negate "works" |
Writing the loop yourself, as the listings do, is usually clearer and makes the bounds explicit.
The teaching implementation
MinCapacity / min_capacity and CanShip / can_ship are written the same way in all four
languages, so the lab highlights the matching lines; the predicate's steps are traced as part of
each test. Every language reads one shared fixture (no packages, one package, one day, more days
than packages, equal weights, weights near the visualization limit) whose expected values come
from a linear scan, not from the binary search. Each language also compares the search with a
linear scan on 1,000 random inputs and checks that the predicate really is monotonic over every
capacity in the range.
Common mistakes
- No monotonicity proof. The search runs fine on a non-monotonic predicate and returns garbage.
- A lower bound that is too low. With
low = 1,canShipwould be asked about capacities that cannot hold the heaviest package; the greedy loop as written then miscounts days instead of failing. - Mixing loop styles.
while low < highgoes withhigh = midandlow = mid + 1; usinglow = midloops forever whenhigh = low + 1. - 32-bit sums.
high = sum(weights)overflows long before the weights look large. - Returning
midinstead oflowafter the loop: the lastmidtested may have failed.
Edge cases
- No packages:
low = high = 0; return 0 without testing. - One day: every test below the total fails; the answer is the total.
- At least as many days as packages: the heaviest package (the lower bound) works.
- All weights equal: the answer is that weight times ⌈n / days⌉.
Worked practice
1. Weights [7, 2, 5, 10, 8], two days. What are the bounds, and what is the answer?
Answer
Bounds [10, 32]. The answer is 18: day 1 takes 7 + 2 + 5 = 14, day 2 takes 10 + 8 = 18. With
17, day 2 would need 10 + 8 = 18 > 17, so a third day is needed.
2. Why is low = mid + 1 safe when canShip(mid) is false?
Answer
By monotonicity, if mid fails, every smaller capacity fails too, so none of low..mid can be the
first working capacity.
3. How many predicate calls does the search need at most when the range holds 1,000 candidates?
Answer
⌈log₂ 1000⌉ = 10. Each call at least halves the range: 1000 → 500 → 250 → 125 → 63 → 32 → 16 → 8 → 4 → 2 → 1.
4. You want the largest capacity that still needs at least 3 days. How does the loop change?
Answer
The predicate "needs ≥ 3 days" is true … true false … false (bigger trucks need fewer days).
Search for the first capacity where it is false, then subtract one; or binary search for the last
true with low = mid and an upward-rounding midpoint mid = low + (high − low + 1) / 2.
Summary
- Binary search needs a monotonic yes/no question, not an array.
- Search on the answer: bounds that surely contain the answer, an O(n) feasibility predicate, and the lower-bound loop for the first true.
- Prove monotonicity for each problem; the code cannot check it for you.
- O(n · log R) instead of O(n · R); keep the range in 64-bit integers in C#, Java and C++.