Greedy Algorithms
Make the locally optimal choice at each step when an exchange argument proves it leads to a global optimum, especially for intervals and scheduling.
Intermediate · about 6 hours · difficulty 3/5
Learn first: Sorting Algorithms, Heaps and Priority Queues
A greedy algorithm builds a solution step by step, always taking the choice that looks best right now, and never reconsidering. When it works it is simple and fast (often just a sort plus a scan). The hard part is knowing when it works.
Proving a greedy choice
- Exchange argument: take any optimal solution that differs from greedy's choice, swap in the greedy choice and show the result is no worse.
- Stays ahead: show greedy's partial solution is always at least as good as any other after each step.
If you cannot find such an argument, try a counterexample; coin change with coins {1, 3, 4} and target 6 breaks the "largest coin first" greedy (4+1+1 vs 3+3).
Classic greedy families
- Interval scheduling: sort by end time and pick non-overlapping intervals (Non-overlapping Intervals, minimum arrows to burst balloons).
- Merging intervals: sort by start and extend.
- Jump game: track the farthest reachable index.
- Resource allocation: assign cookies, boats to save people (sort + two pointers).
- Gas station: if total gas >= total cost, the start is right after the point where the running tank goes negative.
- Heap-based greedy: Huffman coding, task scheduler, IPO.
- Fractional knapsack (greedy by value/weight) vs 0/1 knapsack (needs DP).
Pitfall
Greedy solutions that pass examples but fail hidden tests. Always test against a brute force on small random inputs when unsure.
Key concepts
- Greedy choice property
- Exchange argument proofs
- Interval scheduling by end time
- Merging and inserting intervals
- Jump game reachability
- Heap-driven greedy: Huffman, IPO
- Fractional vs 0/1 knapsack
- Counterexamples and stress testing
Mini project
Solve 9 problems: Jump Game, Jump Game II, Gas Station, Merge Intervals, Insert Interval, Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, Partition Labels, and Candy. For two of them, write a brute force and random stress test.
Check yourself
For maximum non-overlapping intervals, why does sorting by end time work while sorting by start time or by length fails?
Free resources
- Jeff Erickson, Algorithms (Greedy chapter) (UIUC)
- Greedy algorithms (GeeksforGeeks)
- NeetCode Roadmap (Greedy, Intervals) (NeetCode)