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 test.
- Prove the guarantee of greedy for monotone submodular maximization, where greedy approximates instead of solving.
The skeleton of every greedy proof
Induct on the size of the instance . Let be greedy's first choice. By the greedy-choice property, some optimal solution contains it:
By optimal substructure, minus is an optimal solution of the residual instance (for an additive objective; the same argument works for others, such as a maximum):
The rest of greedy's run is greedy on , 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 shape | What you prove | Classic uses |
|---|---|---|
| Greedy stays ahead | A measure of progress in which greedy is never behind any solution, by induction over the steps. | interval scheduling (finish times), Dijkstra (settled distances) |
| Exchange argument | Any 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 bound | A bound every solution must respect, and greedy meets it. | interval partitioning (depth), balloons and arrows (disjoint intervals) |
In interval scheduling, greedy first keeps the interval that finishes earliest. Which residual instance makes optimal substructure work?
- All the intervals except
- The intervals that start at or after
- The intervals that finish after
- The intervals that overlap
Show the answer
B. The intervals that start at or after
After committing to , exactly the intervals compatible with it remain available, and since finishes first, those are the intervals starting at or after . That is again an interval scheduling instance, and an optimal solution containing is 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:
- A local swap inequality: exchanging two adjacent items that are out of comparator order never makes the solution worse.
- Transitivity: the comparator is a total preorder, so a sorted order exists, and any order can be bubble-sorted into it by such swaps.
- Ties: orders that differ only among tied items cost the same.
Part 2 is the one people forget.
Let run immediately before , starting at time . Only these two completion times change when they are swapped:
Subtracting, everything cancels except two cross terms:
So the swap helps exactly when has the smaller ratio. The comparator "" 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:
Jobs A , B and C . Run them by Smith's rule. What is ?
Show the answer
14
The ratios are 3, 0.5 and 1, so the order is B, C, A, finishing at times 1, 3 and 6: . The six possible orders cost between 14 and 25.
Now the greedy for the largest number formed by concatenating integers: put string before string when . The local swap inequality is immediate (swapping adjacent into changes only that stretch of digits, from to the larger ). Transitivity is not obvious at all: string comparisons of different lengths are slippery. It needs a proof.
Read digit strings as numbers with lengths . Concatenation is arithmetic:
Subtract and divide by the positive factors:
So the comparator compares one real number per string, , which is the repeating decimal : , , . Comparing real numbers is transitive. Sorting 3, 30, 34, 5, 9 by decreasing :
Which coin systems are greedy?
A coin system 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, , 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.
Let be the smallest counterexample and suppose . If some optimal payment of used the largest coin , greedy, which also starts with , would be optimal on , because it is optimal on the smaller amount :
So no optimal payment of uses . Take any coin of an optimal payment: then , so , and removing leaves an optimal payment of :
Greedy is optimal on the smaller amount , and its payment starts with . Adding the coin back gives a payment of with coins that uses , a contradiction. Hence:
Checking every amount below by dynamic programming therefore decides canonicity in 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.
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 bestIndices are 0-based here. For the coins 25, 20, 10, 5, 1, the candidate from that keeps no 25 and raises the count of 20s from 1 to 2 is the payment of : two coins against greedy's three (), 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 on the subsets of a finite ground set that is monotone ( implies ) and submodular, with diminishing returns: whenever and . Coverage, the number of elements covered by the chosen sets, is the standard example.
Let be optimal with , and greedy's set after picks. By monotonicity, then submodularity (add the elements of to one at a time):
Greedy's next pick has the largest marginal gain, at least each of the at most terms:
Rearranged:
After picks, using and :
The factor is tight in a strong sense: for maximum coverage, Feige (1998) proved that no polynomial-time algorithm achieves unless P = NP. Likewise, greedy set cover (cover everything with the fewest sets) is within a factor 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 , and the largest-number rule compares the repeating decimals .
- Greedy change-making: the smallest counterexample, if any, lies strictly between and (Kozen and Zaks), and Pearson's test decides canonicity.
- Where greedy cannot be exact it can approximate: 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.
You try to prove the greedy-choice property for shortest interval first by exchange: take an optimal schedule that avoids the shortest interval , and replace an interval of by . Where does the proof break?
- might overlap two intervals of , so making room for it can cost two intervals
- might overlap no interval of , so nothing can be removed
- The residual instance after taking is not an interval scheduling instance
- It does not break: shortest first is optimal
Show the answer
A. might overlap two intervals of , so making room for it can cost two intervals
A short interval can straddle the boundary between two intervals of the optimum. Then inserting forces out both, and the schedule shrinks. is the smallest instance of exactly this.
Why must the comparator " before iff " be shown to be transitive before you sort with it?
- Transitivity is what makes the sort run in time
- Without it, no consistent sorted order need exist, the swap argument cannot reach greedy's order, and a library sort may misbehave
- It is automatically transitive, because string comparison is
- 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 supplies it.
The coins 1, 4, 5 are not canonical. According to Kozen and Zaks, where must the smallest counterexample lie, and what is it?
- Below 5; it is 3
- Strictly between 6 and 9; it is 7
- Strictly between 6 and 9; it is 8
- Above 9; it is 13
Show the answer
C. Strictly between 6 and 9; it is 8
The window is , here , since and . At 7, greedy's is optimal; at 8, greedy uses , four coins, against .
Greedy picks sets, each time the one covering the most still-uncovered elements, to cover as many elements as possible (maximum coverage). What is guaranteed?
- The optimum, by an exchange argument
- At least of the optimum, and nothing better
- Nothing: greedy coverage can be arbitrarily bad
- At least of the optimum, a factor no polynomial-time algorithm can beat unless P = NP
Show the answer
D. At least 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 ; Feige proved that for maximum coverage no polynomial-time algorithm achieves 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.