The Exchange Argument: How to Prove a Greedy Algorithm in an Interview

Interviewers often accept a greedy solution only after you explain why it's correct. "It seems to work on the examples" is the answer that loses points. The exchange argument is a short, reusable way to give a real justification in under a minute.

The template

  1. Let G be your greedy solution and O any optimal solution.
  2. Find the first place where they differ.
  3. Show you can swap O's choice there for G's choice without making O worse.
  4. Repeat: O can be turned into G step by step without losing value, so G is optimal too.

Example 1: maximum non-overlapping intervals

Greedy: sort by end time and always take the interval that ends first. Exchange: if an optimal schedule starts with a different interval, replace it with the one that ends earliest. It ends no later, so it can't conflict with anything that came after; the count stays the same. Repeat for each position.

Example 2: minimizing total waiting time

Serve jobs shortest first. If an optimal order has a longer job immediately before a shorter one, swapping them reduces the waiting time of the shorter job by more than it increases the longer one's, so the total never goes up. An order with no such "inversion" is exactly sorted order.

Example 3: when greedy fails

Coin change with coins {1, 3, 4} and target 6: greedy takes 4+1+1 (three coins), optimal is 3+3 (two). Try the exchange: you can't swap the 4 into the optimal solution without breaking it. Saying this shows the interviewer you test your greedy before trusting it, and it's the cue to switch to dynamic programming.

The counterexample habit

Before proving, spend 30 seconds attacking your own rule with small inputs: ties, one huge item, items that are only slightly better on one dimension. Most wrong greedy ideas die on a three-element example.

What to say out loud

"Take any optimal answer. Where it first disagrees with my choice, I can swap in mine without making it worse, because my choice ends earliest (or is smallest, or has the best ratio). Repeating the swap turns the optimal answer into mine, so mine is optimal."


Disclosure: I help build Linkjob AI copilot, a tool for coding interview practice. This article is independent study material.