Binary Search on the Answer
Turn “minimize the maximum” into a yes-or-no question and search over answers.
Some optimization problems have no clever formula and far too many candidate answers to try, yet one question about them is easy: "can it be done with value ?" If the answer flips only once as grows, about such questions pin down the optimum exactly. A hard optimization problem becomes an easy decision problem, asked thirty or sixty times.
What you’ll learn
- State the binary-search-on-the-answer theorem and prove that evaluations of a monotone check are both sufficient and necessary.
- Solve min-max and max-min problems (shipping within days, splitting an array, spreading items apart) with greedy checks, and prove the checks exact.
- Find the k-th smallest element of a set too large to list (pair distances, the union of two sorted arrays) with a counting check.
- Search over real values and ratios with Dinkelbach's method, and explain how Megiddo's parametric search turns a decision algorithm into an optimization algorithm.
Optimization as a yes/no question
Many optimization problems share a shape. The answer is a number, and for any candidate value it is easy to decide whether is good enough, even when computing the best value directly is not. Can the packages be shipped with capacity ? Can the array be cut so that no part sums to more than ?
If the good-enough values form a ray, so that every value above a good one is also good, the optimum is the boundary of a monotone predicate, and binary search finds it.
Upper bound. Keep the candidates with known to hold (true at the start, ). Testing leaves either or , at most candidates. Since halving with rounding up times leaves , one candidate remains after
Lower bound. Each is the answer for some monotone , the one that turns true at . An algorithm making evaluations sees one of at most sequences of answers, so it can tell apart at most different cases:
Real answers. If is a real number in and you need it within , each evaluation halves an interval instead of a set:
The answer is an integer between 1 and , and one check costs with . How many checks does binary search need in the worst case?
Show the answer
30
, because . Thirty passes over items make steps, a few milliseconds, while trying all values would be hopeless.
Minimize the maximum: shipping and splitting
Shipping within days. Packages with weights leave in this order, and each day the ship carries the next few packages as long as their total stays within its capacity . What is the least that clears everything within days? Below the heaviest package never fits, at one day suffices, and more capacity never hurts. So the search runs over .
def days_needed(w, cap):
"""Days to ship the packages w, in order, carrying at most cap per day (cap >= max(w))."""
days, load = 1, 0
for x in w:
if load + x > cap: # x does not fit today: start a new day
days, load = days + 1, 0
load += x
return days
def min_capacity(w, D):
lo, hi = max(w), sum(w) # lo - 1 never works, hi always does
while lo < hi:
mid = lo + (hi - lo) // 2
if days_needed(w, mid) <= D:
hi = mid # mid works: the answer is mid or smaller
else:
lo = mid + 1 # mid fails, and so does everything below it
return lotime. Note the precondition in the docstring: below this check would quietly give a heavy package a day of its own, so the range must start at .
| days needed | verdict | |||
|---|---|---|---|---|
| 8 | 36 | 22 | 2 | fits: |
| 8 | 22 | 15 | 3 | fits: |
| 8 | 15 | 11 | 5 | too many: |
| 12 | 15 | 13 | 3 | fits: |
| 12 | 13 | 12 | 4 | too many: |
Let greedy's day carry packages , and let any valid schedule's day carry . Claim: greedy is never behind, by induction on .
Step. Assume . If there is nothing to show. Otherwise the block lies inside the other schedule's day , so it fits within , and greedy, which loads every package that fits, reaches at least :
If the other schedule finishes in days, then , so : greedy finishes within days too, and its day count is the minimum.
Splitting an array into contiguous parts so that the largest part sum is as small as possible is the same problem in other words: a part is a day, and the largest part sum is the capacity. The signal is the phrase minimize the maximum. "The maximum is at most " holds exactly when every part fits under , which is a feasibility question with a greedy answer.
Maximize the minimum
Place items on given positions so that the smallest gap between chosen positions is as large as possible. If a gap of is achievable, so is every smaller gap: the property is monotone downward, so search for the last true . The check is greedy again: take the leftmost position, then always the next position at least further on. By the same stays-ahead induction, the -th greedy choice is never to the right of the -th choice of any placement with gaps , so greedy places as many items as any placement can.
def can_place(x, c, d):
"""Can c items go on the sorted positions x with every gap >= d? Greedy, leftmost first."""
count, last = 1, x[0]
for p in x[1:]:
if p - last >= d:
count, last = count + 1, p
return count >= c
def max_min_gap(x, c): # 2 <= c <= len(x)
x = sorted(x)
lo, hi = 0, x[-1] - x[0] + 1 # gap lo is achievable, gap hi is not
while hi - lo > 1:
mid = lo + (hi - lo) // 2
if can_place(x, c, mid):
lo = mid
else:
hi = mid
return lo for coordinates spanning . The loop keeps lo true and hi false and stops when they are adjacent, so it never stalls and needs no rounding tricks.
max_min_gap runs on positions with . It tests , and can_place succeeds by picking 2, 9, 16 and 20. Which update keeps the loop correct?
hi = midlo = mid + 1hi = mid - 1lo = mid
Show the answer
D. lo = mid
A gap of 4 is achievable, so it becomes the new achievable end: lo = mid. The loop then finds that gaps 6 and 5 fail (greedy picks only 2, 9 and 16) and returns 4, the largest achievable minimum gap.
The k-th smallest of a set you cannot list
Some sets are too large to write down: the pairwise distances of points, the entries of a multiplication table, the union of two sorted arrays. To find their k-th smallest element, search over values instead of positions. Let be the number of elements . It never decreases as grows, so "" is monotone, and only has to be fast.
def count_pairs_within(x, d):
"""Pairs i < j of the sorted list x with x[j] - x[i] <= d, by two pointers."""
count, i = 0, 0
for j in range(len(x)):
while x[j] - x[i] > d:
i += 1 # i only moves right as j does
count += j - i
return count
def kth_pair_distance(x, k): # 1 <= k <= n(n-1)/2
x = sorted(x)
lo, hi = 0, x[-1] - x[0] # the answer lies in [lo, hi]
while lo < hi:
mid = lo + (hi - lo) // 2
if count_pairs_within(x, mid) >= k:
hi = mid
else:
lo = mid + 1
return loEach count is one two-pointer pass: as moves right, the leftmost partner within distance never moves left. With coordinates spanning , the total is , against for listing and sorting all the distances.
Think first Points at and . What are and , and what does the search return?
The distances are 2, 3, 4, 5, 7 and 9. Within 4 lie the pairs at distances 2, 3 and 4, so ; within 5 the pair joins them, so . The search returns 5, the fourth smallest distance.
The median of two sorted arrays and , of sizes , is a k-th smallest problem with , and here a sharper search exists: binary search on how many of the smallest come from . If of them come from and from , the split is right exactly when and . The test is monotone in , because grows and shrinks as grows, so probes find the split, with no search over values at all.
import math
def median_two(a, b):
"""Median of the union of the sorted lists a and b (not both empty)."""
if len(a) > len(b):
a, b = b, a
m, n = len(a), len(b)
half = (m + n + 1) // 2 # size of the left part
lo, hi = 0, m # i = how many elements of a go left
while True:
i = lo + (hi - lo) // 2
j = half - i
al = a[i - 1] if i > 0 else -math.inf
ar = a[i] if i < m else math.inf
bl = b[j - 1] if j > 0 else -math.inf
br = b[j] if j < n else math.inf
if al > br:
hi = i - 1 # too many from a
elif bl > ar:
lo = i + 1 # too few from a
else:
left = max(al, bl)
return left if (m + n) % 2 else (left + min(ar, br)) / 2time. The infinite sentinels stand in for parts that are empty.
Real answers, ratios and parametric search
When the answer is a real number, stop after a fixed number of halvings rather than testing hi - lo > eps: in floating point the width can get stuck above any small , as the lesson Ternary Search & Continuous Bisection shows. Sixty to a hundred halvings are typical. A classic real-valued case is fractional programming: maximize a ratio over a finite set of choices , with .
The best ratio is at least exactly when some choice has . So define
Each is a decreasing linear function of , so , their maximum, is decreasing and convex, and it changes sign exactly at the optimum:
Binary search on needs only the sign of , a problem without division. For the largest average of a subarray of length at least , subtract from every element: some such subarray averages at least iff some subarray of length of the shifted values has a nonnegative sum, which prefix sums and a running minimum decide in :
Dinkelbach's method (1967) uses more than the sign. The maximizer of is a candidate whose ratio is at least , so jumping there is a Newton step on the convex, piecewise-linear . On a finite set it reaches after finitely many steps, and it converges superlinearly (Schaible, 1976).
def has_mean_at_least(a, L, t):
"""Is there a subarray of length >= L whose mean is >= t?"""
P = [0.0]
for v in a:
P.append(P[-1] + v - t) # prefix sums of a[i] - t
lowest = float('inf')
for r in range(L, len(a) + 1):
lowest = min(lowest, P[r - L]) # the best start that leaves length >= L
if P[r] - lowest >= 0:
return True
return False
def max_mean(a, L, iters=100):
lo, hi = min(a), max(a) # the optimum lies in [lo, hi]
for _ in range(iters): # a fixed count, not an epsilon test
mid = (lo + hi) / 2
if has_mean_at_least(a, L, mid):
lo = mid
else:
hi = mid
return loper check and in total; tested against brute force over all subarrays.
Key takeaways
- Binary search on the answer turns an optimization problem into about decision problems whenever feasibility is monotone in the value; checks are necessary and sufficient.
- "Minimize the maximum" becomes "can every part stay at most ?", and "maximize the minimum" becomes "can every gap stay at least ?"; greedy checks decide both exactly, by a stays-ahead induction.
- The check must be valid on the whole search range, and the range must contain the answer: start shipping at , not at 1.
- The k-th smallest element of a set too large to list is the least value with , so a fast counting check suffices, and minimality guarantees an actual element.
- Real answers need a fixed number of halvings; ratios reduce to the sign of , Dinkelbach's method takes Newton steps on , and parametric search handles optima that cannot be listed.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
min_capacity starts the search at lo = max(w). What goes wrong if it starts at lo = 1 instead, with days_needed unchanged?
- Nothing: the extra candidates only cost a few more probes
- Below ,
days_neededquietly gives an oversized package a day of its own, can report success, and the search may return an impossible capacity - The loop never terminates
- The search then always returns
Show the answer
B. Below , days_needed quietly gives an oversized package a day of its own, can report success, and the search may return an impossible capacity
For w = [10] and capacity 1, days_needed opens a second day and loads the package anyway, reporting 2 days. With , capacity 1 "passes", and the search returns 1. A check is only as good as its domain: keep the range where the check is valid, or make the check reject capacities below .
For "maximize the minimum gap", let say that items fit with every gap at least . Which statement is correct?
- is monotone: if a gap is achievable, so is every smaller gap, and the answer is the last with true
- is monotone: if a gap is achievable, so is every larger gap
- is not monotone, so the problem needs dynamic programming
- is monotone only when the positions are equally spaced
Show the answer
A. is monotone: if a gap is achievable, so is every smaller gap, and the answer is the last with true
A placement whose gaps are all at least has all gaps at least for any . So the achievable gaps form a prefix , and the search looks for its last element, keeping lo achievable and hi not.
To find the k-th smallest pairwise distance, binary search returns the least with , where counts pairs within distance . The probes include many values that are not distances. Why is the returned value always a genuine distance?
- Because the search probes only values that occur in the set
- It is not: the result has to be rounded to the nearest distance
- Because increases only at values that occur in the set, so the least with is the k-th smallest element itself
- Because the coordinates are integers
Show the answer
C. Because increases only at values that occur in the set, so the least with is the k-th smallest element itself
Let be the k-th smallest distance. Then , while any counts only distances smaller than , at most of them. So the least that reaches is , wherever the probes landed on the way.
You binary search on for the largest average of a subarray of length at least . Which check decides "is the optimum at least ?" in time?
- Average every subarray of length exactly
- Sort the array and average its largest values
- Check whether the whole array averages at least
- Subtract from every element, then test with prefix sums and a running minimum whether some subarray of length has a nonnegative sum
Show the answer
D. Subtract from every element, then test with prefix sums and a running minimum whether some subarray of length has a nonnegative sum
A subarray averages at least exactly when its elements, each reduced by , sum to something nonnegative. With prefix sums , that asks whether for some : one pass with a running minimum.
Further reading
- N. Megiddo, "Applying parallel computation algorithms in the design of serial algorithms," Journal of the ACM 30(4) (1983), 852–865.
- R. Cole, "Slowing down sorting networks to obtain faster sorting algorithms," Journal of the ACM 34(1) (1987), 200–208.
- W. Dinkelbach, "On nonlinear fractional programming," Management Science 13(7) (1967), 492–498.
- T. M. Chan, "Geometric applications of a randomized optimization technique," Discrete & Computational Geometry 22 (1999), 547–567.
- S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020), the sections on binary searching the answer.