Home/Learn/Greedy Algorithms

Pattern Guide

Greedy Algorithms

"Make the locally optimal choice. Hope it's globally optimal."

Greedy works when the locally optimal choice never needs to be revised. Learn how to prove greedy correctness with exchange arguments, and master the interval scheduling, activity selection, and jump game patterns.

Problems you can solve with this pattern

12 problems · click any to start solving

All greedy
1Jump GameMediumSolve
2Jump Game II (minimum jumps)MediumSolve
3Merge IntervalsMediumSolve
4Non-overlapping Intervals (min removals)MediumSolve

Greedy algorithms make the locally optimal decision at each step without reconsidering past choices. The hard part isn't implementation — it's proving the greedy choice is safe. The most common proof technique is the "exchange argument": assume the optimal solution doesn't make our greedy choice, then show that swapping to our choice doesn't make things worse. If you can prove that, greedy is correct.

Greedy works when: there's a greedy-choice property (local optimal → global optimal) AND optimal substructure. Greedy fails when the best local choice at step k prevents a better global solution — that's when you need DP instead.

Pattern Recognition

Problem SignalGreedy Strategy
Interval scheduling (max non-overlapping)Sort by END time, greedily pick earliest-ending
Interval mergingSort by start time, merge overlapping
Jump gameTrack max reachable index, check if target reachable
Meeting rooms (min rooms needed)Two separate sorted arrays: sort starts + ends
Task with deadlinesSort by deadline, use max-heap for scheduling
"Minimum operations to achieve X"Often greedy — pick largest/smallest available each time
Proving greedy correctness — exchange argument:
Assume optimal solution picks X. Show you can swap X for the greedy choice without making things worse. If every swap preserves or improves the solution, greedy is optimal.

Greedy fails when: future consequences of a local choice can't be captured locally. Use DP instead.

Greedy sorting tricks:
- Interval scheduling: sort by END time (keeps most room for future)
- Interval merging: sort by START time (detect overlaps)
- Job sequencing: sort by deadline / profit ratio
- Two-group problems (candy, tasks): two-pass left→right then right→left