Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 vv?" If the answer flips only once as vv grows, about log⁡2(range)\log_2(\text{range}) 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 ⌈log⁡2(R−L+1)⌉\lceil \log_2(R - L + 1) \rceil evaluations of a monotone check are both sufficient and necessary.
  • Solve min-max and max-min problems (shipping within DD 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 vv it is easy to decide whether vv is good enough, even when computing the best value directly is not. Can the packages be shipped with capacity vv? Can the array be cut so that no part sums to more than vv?

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.

DerivationProof
  1. t=⌈log⁡2(R−L+1)⌉  evaluationst = \lceil \log_2 (R - L + 1) \rceil \ \text{ evaluations}

    Upper bound. Keep the ss candidates [lo,hi][lo, hi] with P(hi)P(hi) known to hold (true at the start, hi=Rhi = R). Testing mid=lo+⌊(hi−lo)/2⌋mid = lo + \lfloor (hi - lo)/2 \rfloor leaves either [lo,mid][lo, mid] or [mid+1,hi][mid + 1, hi], at most ⌈s/2⌉\lceil s/2 \rceil candidates. Since halving with rounding up tt times leaves ⌈s/2t⌉\lceil s / 2^t \rceil, one candidate remains after

  2. 2t≥R−L+1⟹t≥⌈log⁡2(R−L+1)⌉2^t \ge R - L + 1 \quad\Longrightarrow\quad t \ge \lceil \log_2 (R - L + 1) \rceil

    Lower bound. Each v∈[L,R]v \in [L, R] is the answer for some monotone PP, the one that turns true at vv. An algorithm making tt evaluations sees one of at most 2t2^t sequences of answers, so it can tell apart at most 2t2^t different cases:

  3. t=⌈log⁡2R−Lε⌉,e.g. R−L=109, ε=10−9: t=60t = \left\lceil \log_2 \tfrac{R - L}{\varepsilon} \right\rceil, \qquad \text{e.g. } R - L = 10^9,\ \varepsilon = 10^{-9}:\ t = 60

    Real answers. If v∗v^* is a real number in [L,R][L, R] and you need it within ε\varepsilon, each evaluation halves an interval instead of a set:

Predict before you look

The answer is an integer between 1 and 10910^9, and one check costs O(n)O(n) with n=2×105n = 2 \times 10^5. How many checks does binary search need in the worst case?

Show the answer

30

⌈log⁡2109⌉=30\lceil \log_2 10^9 \rceil = 30, because 229≈5.4×108<109≤230≈1.07×1092^{29} \approx 5.4 \times 10^8 < 10^9 \le 2^{30} \approx 1.07 \times 10^9. Thirty passes over 2×1052 \times 10^5 items make 6×1066 \times 10^6 steps, a few milliseconds, while trying all 10910^9 values would be hopeless.

Minimize the maximum: shipping and splitting

Shipping within DD days. Packages with weights w0,…,wn−1w_0, \dots, w_{n-1} leave in this order, and each day the ship carries the next few packages as long as their total stays within its capacity cc. What is the least cc that clears everything within DD days? Below max⁡w\max w the heaviest package never fits, at ∑w\sum w one day suffices, and more capacity never hurts. So the search runs over [max⁡w,∑w][\max w, \sum w].

python
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 lo

O(nlog⁡∑w)O(n \log \sum w) time. Note the precondition in the docstring: below max⁡w\max w this check would quietly give a heavy package a day of its own, so the range must start at max⁡w\max w.

lolohihimidmiddays neededverdict
836222fits: hi=22hi = 22
822153fits: hi=15hi = 15
815115too many: lo=12lo = 12
1215133fits: hi=13hi = 13
1213124too many: lo=13lo = 13
The search for w=[4,8,1,7,3,6,2,5]w = [4, 8, 1, 7, 3, 6, 2, 5] and D=3D = 3. Five checks, as the theorem predicts: ⌈log⁡2(36−8+1)⌉=5\lceil \log_2(36 - 8 + 1) \rceil = 5. With capacity 13 the days carry [4,8,1][4, 8, 1], [7,3][7, 3] and [6,2,5][6, 2, 5]; with 12 a fourth day is needed.
DerivationProof: greedy stays ahead
  1. g0=o0=0,gj≥oj  for all jg_0 = o_0 = 0, \qquad g_j \ge o_j \ \text{ for all } j

    Let greedy's day jj carry packages [gj−1,gj)[g_{j-1}, g_j), and let any valid schedule's day jj carry [oj−1,oj)[o_{j-1}, o_j). Claim: greedy is never behind, by induction on jj.

  2. ∑i=gj−1oj−1wi  ≤  ∑i=oj−1oj−1wi  ≤  c⟹gj≥oj\sum_{i = g_{j-1}}^{o_j - 1} w_i \;\le\; \sum_{i = o_{j-1}}^{o_j - 1} w_i \;\le\; c \quad\Longrightarrow\quad g_j \ge o_j

    Step. Assume gj−1≥oj−1g_{j-1} \ge o_{j-1}. If gj−1≥ojg_{j-1} \ge o_j there is nothing to show. Otherwise the block [gj−1,oj)[g_{j-1}, o_j) lies inside the other schedule's day jj, so it fits within cc, and greedy, which loads every package that fits, reaches at least ojo_j:

  3. od=n  ⟹  gd=no_d = n \;\Longrightarrow\; g_d = n

    If the other schedule finishes in dd days, then od=no_d = n, so gd=ng_d = n: greedy finishes within dd days too, and its day count is the minimum.

Splitting an array into kk 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 vv" holds exactly when every part fits under vv, which is a feasibility question with a greedy answer.

Maximize the minimum

Place cc items on nn given positions so that the smallest gap between chosen positions is as large as possible. If a gap of dd is achievable, so is every smaller gap: the property is monotone downward, so search for the last true dd. The check is greedy again: take the leftmost position, then always the next position at least dd further on. By the same stays-ahead induction, the ii-th greedy choice is never to the right of the ii-th choice of any placement with gaps ≥d\ge d, so greedy places as many items as any placement can.

python
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

O(nlog⁡n+nlog⁡W)O(n \log n + n \log W) for coordinates spanning WW. The loop keeps lo true and hi false and stops when they are adjacent, so it never stalls and needs no rounding tricks.

Check your understanding

max_min_gap runs on positions [2,5,9,11,16,20][2, 5, 9, 11, 16, 20] with c=4c = 4. It tests mid=4mid = 4, and can_place succeeds by picking 2, 9, 16 and 20. Which update keeps the loop correct?

  1. hi = mid
  2. lo = mid + 1
  3. hi = mid - 1
  4. lo = 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 (n2)\binom{n}{2} pairwise distances of nn points, the n2n^2 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 count(v)\text{count}(v) be the number of elements ≤v\le v. It never decreases as vv grows, so "count(v)≥k\text{count}(v) \ge k" is monotone, and only count\text{count} has to be fast.

python
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 lo

Each count is one two-pointer pass: as jj moves right, the leftmost partner within distance dd never moves left. With coordinates spanning WW, the total is O(nlog⁡n+nlog⁡W)O(n \log n + n \log W), against O(n2log⁡n)O(n^2 \log n) for listing and sorting all the distances.

Think first Points at 1,3,6,101, 3, 6, 10 and k=4k = 4. What are count(4)\text{count}(4) and count(5)\text{count}(5), 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 count(4)=3<k\text{count}(4) = 3 < k; within 5 the pair (1,6)(1, 6) joins them, so count(5)=4≥k\text{count}(5) = 4 \ge k. The search returns 5, the fourth smallest distance.

The median of two sorted arrays aa and bb, of sizes m≤nm \le n, is a k-th smallest problem with k=⌈(m+n)/2⌉k = \lceil (m + n)/2 \rceil, and here a sharper search exists: binary search on how many of the kk smallest come from aa. If ii of them come from aa and j=k−ij = k - i from bb, the split is right exactly when a[i−1]≤b[j]a[i-1] \le b[j] and b[j−1]≤a[i]b[j-1] \le a[i]. The test a[i−1]>b[j]a[i-1] > b[j] is monotone in ii, because a[i−1]a[i-1] grows and b[k−i]b[k - i] shrinks as ii grows, so O(log⁡m)O(\log m) probes find the split, with no search over values at all.

python
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)) / 2

O(log⁡min⁡(m,n))O(\log \min(m, n)) time. 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 ε\varepsilon, 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 N(x)/D(x)N(x)/D(x) over a finite set of choices xx, with D>0D > 0.

DerivationFrom a ratio to a sign
  1. F(t)=max⁡x(N(x)−t D(x)),λ∗=max⁡xN(x)D(x)F(t) = \max_x \big(N(x) - t\,D(x)\big), \qquad \lambda^* = \max_x \frac{N(x)}{D(x)}

    The best ratio is at least tt exactly when some choice has N(x)−t D(x)≥0N(x) - t\,D(x) \ge 0. So define

  2. F(t)≥0  ⟺  t≤λ∗F(t) \ge 0 \iff t \le \lambda^*

    Each N(x)−t D(x)N(x) - t\,D(x) is a decreasing linear function of tt, so FF, their maximum, is decreasing and convex, and it changes sign exactly at the optimum:

  3. max⁡r−l≥L(Pt[r]−Pt[l])≥0,Pt[i]=∑j<i(aj−t)\max_{r - l \ge L} \big(P_t[r] - P_t[l]\big) \ge 0, \qquad P_t[i] = \sum_{j < i} (a_j - t)

    Binary search on tt needs only the sign of F(t)F(t), a problem without division. For the largest average of a subarray of length at least LL, subtract tt from every element: some such subarray averages at least tt iff some subarray of length ≥L\ge L of the shifted values has a nonnegative sum, which prefix sums and a running minimum decide in O(n)O(n):

  4. ti+1=N(xi)D(xi),xi∈arg max⁡x(N(x)−ti D(x))t_{i+1} = \frac{N(x_i)}{D(x_i)}, \qquad x_i \in \argmax_x \big(N(x) - t_i\,D(x)\big)

    Dinkelbach's method (1967) uses more than the sign. The maximizer xix_i of F(ti)F(t_i) is a candidate whose ratio ti+1t_{i+1} is at least tit_i, so jumping there is a Newton step on the convex, piecewise-linear FF. On a finite set it reaches λ∗\lambda^* after finitely many steps, and it converges superlinearly (Schaible, 1976).

python
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 lo

O(n)O(n) per check and O(nlog⁡max⁡a−min⁡aε)O(n \log \frac{\max a - \min a}{\varepsilon}) in total; tested against brute force over all subarrays.

Key takeaways

  • Binary search on the answer turns an optimization problem into about log⁡2(range)\log_2(\text{range}) decision problems whenever feasibility is monotone in the value; ⌈log⁡2(R−L+1)⌉\lceil \log_2(R - L + 1) \rceil checks are necessary and sufficient.
  • "Minimize the maximum" becomes "can every part stay at most vv?", and "maximize the minimum" becomes "can every gap stay at least vv?"; 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 max⁡w\max w, not at 1.
  • The k-th smallest element of a set too large to list is the least value vv with count(v)≥k\text{count}(v) \ge k, 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 F(t)=max⁡x(N(x)−t D(x))F(t) = \max_x (N(x) - t\,D(x)), Dinkelbach's method takes Newton steps on FF, 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.

Question 1

min_capacity starts the search at lo = max(w). What goes wrong if it starts at lo = 1 instead, with days_needed unchanged?

  1. Nothing: the extra candidates only cost a few more probes
  2. Below max⁡w\max w, days_needed quietly gives an oversized package a day of its own, can report success, and the search may return an impossible capacity
  3. The loop never terminates
  4. The search then always returns max⁡w\max w
Show the answer

B. Below max⁡w\max w, 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 D=2D = 2, 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 max⁡w\max w.

Question 2

For "maximize the minimum gap", let g(d)g(d) say that cc items fit with every gap at least dd. Which statement is correct?

  1. gg is monotone: if a gap dd is achievable, so is every smaller gap, and the answer is the last dd with g(d)g(d) true
  2. gg is monotone: if a gap dd is achievable, so is every larger gap
  3. gg is not monotone, so the problem needs dynamic programming
  4. gg is monotone only when the positions are equally spaced
Show the answer

A. gg is monotone: if a gap dd is achievable, so is every smaller gap, and the answer is the last dd with g(d)g(d) true

A placement whose gaps are all at least dd has all gaps at least d′d' for any d′<dd' < d. So the achievable gaps form a prefix [0,d∗][0, d^*], and the search looks for its last element, keeping lo achievable and hi not.

Question 3

To find the k-th smallest pairwise distance, binary search returns the least vv with count(v)≥k\text{count}(v) \ge k, where count(v)\text{count}(v) counts pairs within distance vv. The probes include many values that are not distances. Why is the returned value always a genuine distance?

  1. Because the search probes only values that occur in the set
  2. It is not: the result has to be rounded to the nearest distance
  3. Because count\text{count} increases only at values that occur in the set, so the least vv with count(v)≥k\text{count}(v) \ge k is the k-th smallest element itself
  4. Because the coordinates are integers
Show the answer

C. Because count\text{count} increases only at values that occur in the set, so the least vv with count(v)≥k\text{count}(v) \ge k is the k-th smallest element itself

Let sks_k be the k-th smallest distance. Then count(sk)≥k\text{count}(s_k) \ge k, while any v<skv < s_k counts only distances smaller than sks_k, at most k−1k - 1 of them. So the least vv that reaches kk is sks_k, wherever the probes landed on the way.

Question 4

You binary search on tt for the largest average of a subarray of length at least LL. Which check decides "is the optimum at least tt?" in O(n)O(n) time?

  1. Average every subarray of length exactly LL
  2. Sort the array and average its LL largest values
  3. Check whether the whole array averages at least tt
  4. Subtract tt from every element, then test with prefix sums and a running minimum whether some subarray of length ≥L\ge L has a nonnegative sum
Show the answer

D. Subtract tt from every element, then test with prefix sums and a running minimum whether some subarray of length ≥L\ge L has a nonnegative sum

A subarray averages at least tt exactly when its elements, each reduced by tt, sum to something nonnegative. With prefix sums PtP_t, that asks whether Pt[r]−min⁡l≤r−LPt[l]≥0P_t[r] - \min_{l \le r - L} P_t[l] \ge 0 for some rr: 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.