Greedy Algorithms
Recognise when a locally best choice leads to a global optimum, and solve interval, scheduling and jump problems greedily.
Intermediate · about 6 hours · difficulty 3/5
Learn first: Sorting Algorithms and Custom Sorts, Heaps and Priority Queues
A greedy algorithm makes the best-looking choice at each step and never revisits it. It is fast and short, but it is only correct when you can argue that the choice is safe.
Key patterns
- Interval scheduling: sort by end time and take the earliest finishing interval (Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, N meetings in one room).
- Sort and match: Assign Cookies, Boats to Save People (two pointers after sorting).
- Reachability: Jump Game (track furthest reach), Jump Game II (BFS-like levels).
- Running balance: Gas Station (restart after a negative tank), Lemonade Change.
- Exchange argument: Fractional Knapsack by value per weight, Job Sequencing with deadlines.
- Two passes: Candy (left-to-right, then right-to-left).
- Huffman coding uses a heap and greedy merging.
Proving it
Use an exchange argument: take any optimal solution, swap in your greedy choice, and show the result is no worse. If you cannot argue it, try a small counterexample. Coin change with coins {1, 3, 4} and amount 6 breaks the "largest coin first" greedy, which is why it needs DP.
Pitfalls
- Sorting by the wrong key (start time instead of end time in interval scheduling).
- Applying greedy to 0/1 knapsack, which needs DP.
You are ready to move on when you can solve Non-overlapping Intervals and Gas Station and justify each greedy choice in one sentence.
Key concepts
- Greedy choice property
- Interval scheduling
- Jump Game family
- Exchange arguments
- Fractional knapsack and job sequencing
- Counterexamples to greedy
- Huffman coding
Mini project
Solve these 10 in 7 days, log time and pattern: Assign Cookies, Lemonade Change, Jump Game, Jump Game II, Gas Station, Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, Boats to Save People, Candy, Job Sequencing Problem (GfG).
Check yourself
Give a coin set and amount where picking the largest coin first gives a wrong answer.
Free resources
- takeUforward greedy series (takeUforward)
- Competitive Programmer's Handbook (Ch. 6) (CSES)
- NeetCode roadmap: Greedy (NeetCode)