Advanced · Module 16 · Lesson 2 of 4
Exchange arguments
To prove a greedy order is optimal, take any solution that differs from it, swap two elements to make it more like the greedy one, and show the swap never makes it worse. Repeat until the two agree.
By the end you can
- Prove a greedy ordering optimal with an adjacent-swap exchange argument
- Derive a sorting key or comparator from what a swap changes
- Recognize when an exchange makes things worse, which disproves a greedy rule
Builds on When greedy works.
01 · A question first
Five customers wait for one barber, needing 30, 10, 20, 5 and 15 minutes. Serving the shortest haircut first minimizes the total time customers spend in the shop. How can you be sure no clever order does better, without checking all 120 orders?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Proving a greedy rule
- Shortest job first
- The swap tells you the sort key
- When the exchange hurts
- Exchange arguments without sorting
- Writing the proof
- Pseudocode & Multi-Language Implementations (C++, Java, Python)
- Complexity Derivation, Edge Cases & Common Mistakes
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem