Sub topic 6
Proving Correctness: The Exchange Argument
This chapter assumes you can write and run Python functions and that you know proof by contradiction and proof by induction. It also assumes you have read the earlier chapters on the greedy choice property and optimal substructure. In the "greedy stays ahead" technique, you track the greedy solution step by step and show it never falls behind. The exchange argument works the other way: you start from an optimal solution and change it, one small step at a time, until it becomes the greedy solution, and you show that no step makes it worse.
The Core Idea
A greedy algorithm commits to choices it never revisits. To prove it correct, you must rule out a cleverer solution that beats it. The exchange argument does this indirectly:
- Let
Obe any optimal solution andGthe greedy solution. - If
Odiffers fromG, find a specific difference. This is often a pair of elements in the "wrong" order, or the first position where they disagree. - Swap, or exchange, elements of
Oto remove that difference. The result isO'. - Prove that
O'is still valid and that its cost is no worse than the cost ofO. - Repeat. Each exchange reduces a measure of difference, so the process ends at
G. Every step kept optimality, soGis optimal.
The proof never builds O itself. It only needs local facts about what one swap does.
A Worked Example: Minimizing Total Completion Time
Later chapters use this technique on fractional knapsack, minimizing lateness, Huffman coding, and spanning trees. Here we use a small problem that none of those chapters covers, so the proof structure is easy to see.
Problem. One machine has n jobs to run. Job i takes p_i time units. Jobs run one after another with no gaps. The completion time C_i of a job is the moment it finishes. Find an order that minimizes the sum of all C_i.
Greedy rule. Run the shortest job first (Shortest Processing Time, or SPT). In code, that means sorting by p_i.
from itertools import permutations
def total_completion(order):
t = 0
total = 0
for p in order:
t += p
total += t
return total
def spt(jobs):
return sorted(jobs)
jobs = [3, 1, 4, 2]
greedy = spt(jobs)
best = min(permutations(jobs), key=total_completion)
print(greedy, total_completion(greedy)) # [1, 2, 3, 4] 20
print(best, total_completion(best)) # (1, 2, 3, 4) 20A brute-force check on one input is not a proof, but it is worth running before you write one. If the greedy rule fails on a small case, the brute force shows you a counterexample right away.
Step 1: Define the difference
An inversion in a schedule is a pair of jobs i and j where i runs before j but p_i > p_j. The SPT schedule has no inversions. Any schedule that is not sorted has at least one inversion. It also has at least one adjacent inversion, meaning two consecutive jobs out of order. If every consecutive pair were in order, the whole sequence would be sorted.
Step 2: Analyze one swap
Take an optimal schedule O with an adjacent inversion: job i runs right before job j, and p_i > p_j. Let T be the time when i starts. Swap the two jobs to get O'.
| Job | Finish in `O` | Finish in `O'` |
|---|---|---|
| Jobs before `i` | unchanged | unchanged |
| `i` | `T + p_i` | `T + p_j + p_i` |
| `j` | `T + p_i + p_j` | `T + p_j` |
| Jobs after `j` | unchanged | unchanged |
The pair still occupies the same block of time, from T to T + p_i + p_j, so every other job finishes at the same time as before. Only the two swapped jobs change:
- In
O, the pair contributes(T + p_i) + (T + p_i + p_j) = 2T + 2p_i + p_j. - In
O', the pair contributes(T + p_j) + (T + p_i + p_j) = 2T + p_i + 2p_j.
The change is p_j - p_i, which is negative. So the swap strictly lowers the total, and O was not optimal after all. This contradicts our assumption, so an optimal schedule has no inversions.
Step 3: Handle ties and conclude
If p_i = p_j, the pair is not an inversion and the swap changes nothing. Every schedule with no inversions is therefore SPT order, up to how equal-length jobs are ordered among themselves. All such orderings have the same cost. An optimal schedule exists, because there are finitely many orders, and it must be one of these. So SPT is optimal.
Each adjacent swap removes exactly one inversion, and a schedule has at most n(n-1)/2 inversions. So the "repeat until equal to G" loop always ends. You need this termination fact whenever you choose the version of the proof that says "transform O step by step into G" instead of the version that says "assume O has an inversion and derive a contradiction."
You can check the swap analysis with code:
import random
def swap_delta(order, k):
swapped = order[:k] + [order[k + 1], order[k]] + order[k + 2:]
return total_completion(swapped) - total_completion(order)
for _ in range(1000):
order = [random.randint(1, 20) for _ in range(6)]
k = random.randrange(5)
assert swap_delta(order, k) == order[k + 1] - order[k]
print("swap delta always equals p_j - p_i")Two Shapes of the Argument
You will see exchange proofs written in two common forms. Both rely on the same swap analysis.
| Form | What you track | Typical use |
|---|---|---|
| Inversion removal | Number of out-of-order pairs | Ordering problems: completion time, lateness |
| First difference | First position where `O` and `G` disagree | Selection problems: knapsack, spanning trees, Huffman merges |
In the first-difference form, let k be the first index where O differs from G. Change O so that it agrees with G at index k without breaking any earlier agreement, and show the cost does not increase. Induction on k finishes the proof. This form connects directly to the greedy choice property: the first difference is exactly the first greedy choice that O did not make. Showing that you can make O take that choice at no cost is the claim that "some optimal solution contains the greedy choice."
Common Errors
- Forgetting validity. The exchanged solution must still satisfy all constraints. In scheduling, a swap rarely breaks feasibility. In selection problems such as spanning trees, swapping one edge for another can create a cycle, and the proof has to rule that out.
- Using "strictly better" when ties exist. If a swap can leave the cost unchanged, a contradiction argument based on strict improvement does not work. Use "no worse" together with a termination measure instead.
- No termination measure. "Keep swapping until it matches greedy" is a proof only if something, such as the inversion count or the first-difference index, moves monotonically toward
G. - Assuming the greedy solution is unique. If several greedy outputs are possible because of ties, the proof must cover every tie-breaking rule. Otherwise you must fix one rule and say so.
- Proving the wrong direction. Showing that changing
Gmakes it worse proves only thatGis a local optimum. The exchange has to start from an arbitrary optimalO.
When the Argument Cannot Be Made
The exchange argument fails exactly when no local swap is guaranteed to be safe. For coins {1, 3, 4} and amount 6, the optimal solution [3, 3] contains no 4. Replacing coins to include a 4 forces [4, 1, 1], which uses more coins. Because the swap step breaks down, you have no proof, and as the counterexample chapter showed, greedy is in fact wrong for this coin set. If you try to write the swap step and get stuck, look for a counterexample there.
Exercise
Each job now has a weight wi > 0, and you want to minimize the weighted sum of wi * C_i. Use an exchange argument on an adjacent pair, i immediately before j, to find the greedy ordering rule.
Show answer
Only the pair's terms change. Before the swap, the pair contributes wi(T + pi) + wj(T + pi + pj). After the swap, it contributes wj(T + pj) + wi(T + pj + pi). The change after minus before is wi*pj - wj*pi. The swap helps when wi*pj < wj*pi, which is when pj/wj < pi/wi. So sort jobs by pi/wi in increasing order (Smith's rule). An optimal schedule has no adjacent pair with a larger ratio first, and ties in ratio do not change the cost.
Exercise
A classmate proves SPT optimal like this: "Take any inversion i before j with pi > pj and swap them. Only i and j change finish times, so the total drops by pi - pj." What is wrong, and how do you fix it?
Show answer
If i and j are not adjacent, every job between them finishes pi - pj earlier after the swap, so the claim that only i and j change is false. The total change is also not pi - pj. Fix it by noting that any unsorted schedule has an adjacent inversion and applying the swap only to that adjacent pair, where the change is exactly pj - pi.
Exercise
Suppose you want to maximize total completion time instead. Without writing new code, state the greedy rule and justify it with the swap result from this chapter.
Show answer
Run the longest job first. Swapping an adjacent pair where the shorter job comes first changes the total by plonger - pshorter, which is positive. So any schedule with a shorter job directly before a longer one can be improved. The maximum is therefore reached by sorting in decreasing order of processing time, with ties in any order.