Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Proving Greedy Algorithms Correct

Exchange arguments, “greedy stays ahead”, and finding counterexamples.

Every correct greedy algorithm has a proof, and almost every proof has one of three shapes: greedy stays ahead, an exchange argument, or a matching lower bound. This lesson makes them precise, shows that a sorting-based greedy is only as sound as the transitivity of its comparator, and ends with a question that sounds easy: for which coin systems is greedy change-making optimal?

What you’ll learn

  • State the greedy-choice property and optimal substructure, and prove that together they make a greedy algorithm optimal.
  • Choose between stays-ahead, exchange and lower-bound proofs for a new greedy, and use a failed proof to find a counterexample.
  • Prove a sorting-based greedy by adjacent swaps, including the transitivity of its comparator, for Smith's rule and the largest concatenation.
  • Decide whether greedy change-making is optimal for a coin system, with Kozen and Zaks's bound and Pearson's O(n3)O(n^3) test.
  • Prove the (1−1/e)(1 - 1/e) guarantee of greedy for monotone submodular maximization, where greedy approximates instead of solving.

The skeleton of every greedy proof

DerivationWhy the two properties suffice
  1. c∈Oc \in O

    Induct on the size of the instance II. Let cc be greedy's first choice. By the greedy-choice property, some optimal solution OO contains it:

  2. OPT(I)=val(c)+OPT(Ic)\mathrm{OPT}(I) = \mathrm{val}(c) + \mathrm{OPT}(I_c)

    By optimal substructure, OO minus cc is an optimal solution of the residual instance (for an additive objective; the same argument works for others, such as a maximum):

  3. val(Greedy(I))=val(c)+OPT(Ic)=OPT(I)\mathrm{val}\big(\mathrm{Greedy}(I)\big) = \mathrm{val}(c) + \mathrm{OPT}(I_c) = \mathrm{OPT}(I)

    The rest of greedy's run is greedy on IcI_c, a smaller instance of the same problem, so by induction it is optimal there:

In practice the greedy-choice property is proved in one of three ways, and the residual instance is usually obvious once the first choice is safe:

Proof shapeWhat you proveClassic uses
Greedy stays aheadA measure of progress in which greedy is never behind any solution, by induction over the steps.interval scheduling (finish times), Dijkstra (settled distances)
Exchange argumentAny optimal solution can be transformed into greedy's, one exchange at a time, without getting worse.EDF, fractional knapsack, Huffman, minimum spanning trees (the cut property)
Matching lower boundA bound every solution must respect, and greedy meets it.interval partitioning (depth), balloons and arrows (disjoint intervals)
Check your understanding

In interval scheduling, greedy first keeps the interval gg that finishes earliest. Which residual instance makes optimal substructure work?

  1. All the intervals except gg
  2. The intervals that start at or after f(g)f(g)
  3. The intervals that finish after f(g)f(g)
  4. The intervals that overlap gg
Show the answer

B. The intervals that start at or after f(g)f(g)

After committing to gg, exactly the intervals compatible with it remain available, and since gg finishes first, those are the intervals starting at or after f(g)f(g). That is again an interval scheduling instance, and an optimal solution containing gg is gg plus an optimal solution for it.

Adjacent swaps, and comparators that must be transitive

Many greedies read "sort by a clever comparator, then take everything in that order". A proof has three parts:

  1. A local swap inequality: exchanging two adjacent items that are out of comparator order never makes the solution worse.
  2. Transitivity: the comparator is a total preorder, so a sorted order exists, and any order can be bubble-sorted into it by such swaps.
  3. Ties: orders that differ only among tied items cost the same.

Part 2 is the one people forget.

DerivationProof: the swap inequality
  1. before: wi(T+ti)+wj(T+ti+tj),after: wj(T+tj)+wi(T+tj+ti)\text{before: } w_i(T + t_i) + w_j(T + t_i + t_j),\qquad \text{after: } w_j(T + t_j) + w_i(T + t_j + t_i)

    Let ii run immediately before jj, starting at time TT. Only these two completion times change when they are swapped:

  2. before−after=wjti−witj\text{before} - \text{after} = w_j t_i - w_i t_j

    Subtracting, everything cancels except two cross terms:

  3. wjti>witj  ⟺  tjwj<tiwiw_j t_i > w_i t_j \iff \frac{t_j}{w_j} < \frac{t_i}{w_i}

    So the swap helps exactly when jj has the smaller ratio. The comparator "t/wt/w" compares real numbers, hence is transitive, and every order can be bubble-sorted into ratio order without the cost ever rising; jobs with equal ratios can be swapped at no cost:

Predict before you look

Jobs A (t=3, w=1)(t = 3,\ w = 1), B (t=1, w=2)(t = 1,\ w = 2) and C (t=2, w=2)(t = 2,\ w = 2). Run them by Smith's rule. What is ∑jwjCj\sum_j w_j C_j?

Show the answer

14

The ratios t/wt/w are 3, 0.5 and 1, so the order is B, C, A, finishing at times 1, 3 and 6: 2⋅1+2⋅3+1⋅6=142 \cdot 1 + 2 \cdot 3 + 1 \cdot 6 = 14. The six possible orders cost between 14 and 25.

Now the greedy for the largest number formed by concatenating integers: put string aa before string bb when ab>baab > ba. The local swap inequality is immediate (swapping adjacent b,ab, a into a,ba, b changes only that stretch of digits, from baba to the larger abab). Transitivity is not obvious at all: string comparisons of different lengths are slippery. It needs a proof.

DerivationThe concatenation comparator is transitive
  1. ab=a⋅10∣b∣+b,ba=b⋅10∣a∣+aab = a \cdot 10^{|b|} + b,\qquad ba = b \cdot 10^{|a|} + a

    Read digit strings as numbers a,ba, b with lengths ∣a∣,∣b∣|a|, |b|. Concatenation is arithmetic:

  2. ab>ba  ⟺  a (10∣b∣−1)>b (10∣a∣−1)  ⟺  a10∣a∣−1>b10∣b∣−1ab > ba \iff a\,(10^{|b|} - 1) > b\,(10^{|a|} - 1) \iff \frac{a}{10^{|a|} - 1} > \frac{b}{10^{|b|} - 1}

    Subtract and divide by the positive factors:

  3. 9, 5, 34, 3, 30⟹95343309,\ 5,\ 34,\ 3,\ 30\quad\Longrightarrow\quad 9534330

    So the comparator compares one real number per string, φ(a)=a/(10∣a∣−1)\varphi(a) = a / (10^{|a|} - 1), which is the repeating decimal 0.aaa…0.aaa\ldots: φ(3)=0.333…\varphi(3) = 0.333\ldots, φ(30)=0.3030…\varphi(30) = 0.3030\ldots, φ(34)=0.3434…\varphi(34) = 0.3434\ldots. Comparing real numbers is transitive. Sorting 3, 30, 34, 5, 9 by decreasing φ\varphi:

Which coin systems are greedy?

A coin system 1=c1<c2<⋯<cm1 = c_1 < c_2 < \dots < c_m is canonical if greedy (largest coin first) pays every amount with the fewest coins. The US coins 1, 5, 10, 25 are canonical; 1, 3, 4 are not (6 = 3 + 3); and adding a 20 to the US coins breaks canonicity (40 = 20 + 20). Systems with at most two coins, {1,c}\{1, c\}, are always canonical.

For arbitrary coins, paying with the fewest coins is NP-hard when the coin values are written in binary, though only weakly: dynamic programming over the amounts is pseudo-polynomial. Canonical systems are exactly those where the trivial algorithm is also exact, so recognizing them is worth an algorithm.

DerivationProof of the upper bound
  1. greedy(x)=1+greedy(x−cm)=1+opt(x−cm)=opt(x)\mathrm{greedy}(x) = 1 + \mathrm{greedy}(x - c_m) = 1 + \mathrm{opt}(x - c_m) = \mathrm{opt}(x)

    Let xx be the smallest counterexample and suppose x≥cm+cm−1x \ge c_m + c_{m-1}. If some optimal payment of xx used the largest coin cmc_m, greedy, which also starts with cmc_m, would be optimal on xx, because it is optimal on the smaller amount x−cmx - c_m:

  2. opt(x−c)=opt(x)−1,x−c ≥ cm\mathrm{opt}(x - c) = \mathrm{opt}(x) - 1,\qquad x - c\ \ge\ c_m

    So no optimal payment of xx uses cmc_m. Take any coin cc of an optimal payment: then c≤cm−1c \le c_{m-1}, so x−c≥cmx - c \ge c_m, and removing cc leaves an optimal payment of x−cx - c:

  3. x < cm+cm−1x\ <\ c_m + c_{m-1}

    Greedy is optimal on the smaller amount x−cx - c, and its payment starts with cmc_m. Adding the coin cc back gives a payment of xx with opt(x)\mathrm{opt}(x) coins that uses cmc_m, a contradiction. Hence:

Checking every amount below cm+cm−1c_m + c_{m-1} by dynamic programming therefore decides canonicity in O(m (cm+cm−1))O(m\,(c_m + c_{m-1})) time. That is pseudo-polynomial: coin values can be exponential in the length of their description. Pearson found a test whose cost depends only on the number of coins.

python
def greedy_counts(coins, x):              # coins in decreasing order, coins[-1] == 1
    counts = []
    for c in coins:
        counts.append(x // c)
        x %= c
    return counts

def smallest_counterexample(coins):       # None if greedy is always optimal
    n, best = len(coins), None
    for i in range(1, n):                 # candidates built from G(coins[i-1] - 1)
        g = greedy_counts(coins, coins[i - 1] - 1)
        for j in range(i, n):             # keep g[:j], one more coins[j], nothing smaller
            cand = g[:j] + [g[j] + 1] + [0] * (n - j - 1)
            w = sum(k * c for k, c in zip(cand, coins))
            if sum(greedy_counts(coins, w)) > sum(cand) and (best is None or w < best):
                best = w
    return best

Indices are 0-based here. For the coins 25, 20, 10, 5, 1, the candidate from G(24)=(0,1,0,0,4)G(24) = (0, 1, 0, 0, 4) that keeps no 25 and raises the count of 20s from 1 to 2 is the payment 20+2020 + 20 of w=40w = 40: two coins against greedy's three (25+10+525 + 10 + 5), so the function returns 40. For 25, 10, 5, 1 it returns None.

When greedy can only approximate

Most NP-hard optimization problems have no exact greedy, but greedy often comes provably close. The cleanest setting is a set function ff on the subsets of a finite ground set that is monotone (A⊆BA \subseteq B implies f(A)≤f(B)f(A) \le f(B)) and submodular, with diminishing returns: f(A∪{x})−f(A)≥f(B∪{x})−f(B)f(A \cup \{x\}) - f(A) \ge f(B \cup \{x\}) - f(B) whenever A⊆BA \subseteq B and x∉Bx \notin B. Coverage, the number of elements covered by the chosen sets, is the standard example.

DerivationProof: every pick closes a 1/k fraction of the gap
  1. f(O) ≤ f(Si∪O) ≤ f(Si)+∑o∈O(f(Si∪{o})−f(Si))f(O)\ \le\ f(S_i \cup O)\ \le\ f(S_i) + \sum_{o \in O}\big(f(S_i \cup \{o\}) - f(S_i)\big)

    Let OO be optimal with ∣O∣≤k|O| \le k, and SiS_i greedy's set after ii picks. By monotonicity, then submodularity (add the elements of OO to SiS_i one at a time):

  2. f(O)−f(Si) ≤ k (f(Si+1)−f(Si))f(O) - f(S_i)\ \le\ k\,\big(f(S_{i+1}) - f(S_i)\big)

    Greedy's next pick has the largest marginal gain, at least each of the at most kk terms:

  3. f(O)−f(Si+1) ≤ (1−1k)(f(O)−f(Si))f(O) - f(S_{i+1})\ \le\ \Big(1 - \frac{1}{k}\Big)\big(f(O) - f(S_i)\big)

    Rearranged:

  4. f(O)−f(Sk) ≤ (1−1k)kf(O) ≤ f(O)ef(O) - f(S_k)\ \le\ \Big(1 - \frac{1}{k}\Big)^{k} f(O)\ \le\ \frac{f(O)}{e}

    After kk picks, using (1−1/k)k≤1/e(1 - 1/k)^k \le 1/e and f(∅)≥0f(\emptyset) \ge 0:

The factor is tight in a strong sense: for maximum coverage, Feige (1998) proved that no polynomial-time algorithm achieves 1−1/e+ε1 - 1/e + \varepsilon unless P = NP. Likewise, greedy set cover (cover everything with the fewest sets) is within a factor Hn=1+12+⋯+1n≤1+ln⁡nH_n = 1 + \tfrac12 + \dots + \tfrac1n \le 1 + \ln n of optimal, essentially the best possible in polynomial time. Both belong to Approximation Algorithms.

Key takeaways

  • The greedy-choice property plus optimal substructure (with residual instances of the same problem) make greedy optimal, by induction on the instance size.
  • Three proof shapes cover almost everything: greedy stays ahead, exchange arguments, and a lower bound that greedy meets; a failed exchange usually points straight at a counterexample.
  • A sorting-based greedy needs a local swap inequality and a transitive comparator: Smith's rule compares t/wt/w, and the largest-number rule compares the repeating decimals 0.aaa…0.aaa\ldots.
  • Greedy change-making: the smallest counterexample, if any, lies strictly between c3+1c_3 + 1 and cm+cm−1c_m + c_{m-1} (Kozen and Zaks), and Pearson's O(n3)O(n^3) test decides canonicity.
  • Where greedy cannot be exact it can approximate: 1−1/e1 - 1/e for monotone submodular maximization under a cardinality constraint, which is tight for maximum coverage unless P = NP.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You try to prove the greedy-choice property for shortest interval first by exchange: take an optimal schedule OO that avoids the shortest interval gg, and replace an interval of OO by gg. Where does the proof break?

  1. gg might overlap two intervals of OO, so making room for it can cost two intervals
  2. gg might overlap no interval of OO, so nothing can be removed
  3. The residual instance after taking gg is not an interval scheduling instance
  4. It does not break: shortest first is optimal
Show the answer

A. gg might overlap two intervals of OO, so making room for it can cost two intervals

A short interval can straddle the boundary between two intervals of the optimum. Then inserting gg forces out both, and the schedule shrinks. [0,6),[5,7),[6,12)[0, 6), [5, 7), [6, 12) is the smallest instance of exactly this.

Question 2

Why must the comparator "aa before bb iff ab>baab > ba" be shown to be transitive before you sort with it?

  1. Transitivity is what makes the sort run in O(nlog⁡n)O(n \log n) time
  2. Without it, no consistent sorted order need exist, the swap argument cannot reach greedy's order, and a library sort may misbehave
  3. It is automatically transitive, because string comparison is
  4. Only to break ties between equal strings
Show the answer

B. Without it, no consistent sorted order need exist, the swap argument cannot reach greedy's order, and a library sort may misbehave

The local swap inequality says each swap toward comparator order helps, but that only proves anything if a comparator order exists and can be reached by such swaps, which needs a total preorder. Here the map φ(a)=a/(10∣a∣−1)\varphi(a) = a/(10^{|a|} - 1) supplies it.

Question 3

The coins 1, 4, 5 are not canonical. According to Kozen and Zaks, where must the smallest counterexample lie, and what is it?

  1. Below 5; it is 3
  2. Strictly between 6 and 9; it is 7
  3. Strictly between 6 and 9; it is 8
  4. Above 9; it is 13
Show the answer

C. Strictly between 6 and 9; it is 8

The window is c3+1<x<cm+cm−1c_3 + 1 < x < c_m + c_{m-1}, here 6<x<96 < x < 9, since c3=cm=5c_3 = c_m = 5 and cm−1=4c_{m-1} = 4. At 7, greedy's 5+1+15 + 1 + 1 is optimal; at 8, greedy uses 5+1+1+15 + 1 + 1 + 1, four coins, against 4+44 + 4.

Question 4

Greedy picks kk sets, each time the one covering the most still-uncovered elements, to cover as many elements as possible (maximum coverage). What is guaranteed?

  1. The optimum, by an exchange argument
  2. At least 1/k1/k of the optimum, and nothing better
  3. Nothing: greedy coverage can be arbitrarily bad
  4. At least 1−1/e≈63%1 - 1/e \approx 63\% of the optimum, a factor no polynomial-time algorithm can beat unless P = NP
Show the answer

D. At least 1−1/e≈63%1 - 1/e \approx 63\% of the optimum, a factor no polynomial-time algorithm can beat unless P = NP

Coverage is monotone and submodular, so Nemhauser, Wolsey and Fisher's bound gives (1−1/e) OPT(1 - 1/e)\,\mathrm{OPT}; Feige proved that for maximum coverage no polynomial-time algorithm achieves 1−1/e+ε1 - 1/e + \varepsilon unless P = NP.

Further reading

  • W. E. Smith, "Various optimizers for single-stage production," Naval Research Logistics Quarterly 3 (1956), 59–66.
  • D. Kozen & S. Zaks, "Optimal bounds for the change-making problem," Theoretical Computer Science 123 (1994), 377–388.
  • D. Pearson, "A polynomial-time algorithm for the change-making problem," Operations Research Letters 33(3) (2005), 231–234.
  • G. L. Nemhauser, L. A. Wolsey & M. L. Fisher, "An analysis of approximations for maximizing submodular set functions—I," Mathematical Programming 14 (1978), 265–294.
  • J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 4.