A greedy algorithm builds a solution one step at a time, always taking the choice that looks best right now and never revisiting it. When it works, it is usually the simplest and fastest solution available, often a sort followed by one pass. The catch is that it works only for problems with the right structure, so the real skill is knowing when a greedy choice is safe and being able to prove it.
Think of it like
Packing a day with meetings
You want to attend as many one-hour-or-longer meetings as possible, and they overlap. A good rule: always go to the meeting that ends first, then pick the next one that starts after it ends. Leaving early keeps the most of your day free for everything else. That rule is provably optimal, while tempting alternatives such as "shortest meeting first" are not.
How greedy works
A greedy algorithm repeats one move: pick the locally best option according to some rule, commit to it, and reduce the problem to a smaller one. There is no backtracking and no table of subproblems, so greedy algorithms are typically O(n log n), dominated by an initial sort or by heap operations, followed by a linear pass.
- Greedy-choice property
- Some optimal solution begins with the greedy choice. Committing to it never rules out an optimum.
- Optimal substructure
- After making the greedy choice, the remaining problem is a smaller instance whose optimal solution, combined with the choice, is optimal overall.
- Exchange argument
- Take any optimal solution that differs from greedy, swap one of its choices for the greedy one, and show it stays feasible and no worse.
- Greedy stays ahead
- Show that after every step, greedy's partial solution is at least as good as any other algorithm's after the same number of steps.
How to recognize it
- The problem asks for a maximum or minimum count or cost, and choices can be ordered by an obvious key (end time, ratio, deadline, size).
- Intervals: schedule, merge, cover, remove overlaps, shoot balloons.
- "Can you reach the end?" or "minimum number of steps" where only the farthest reach matters.
- Matching two sorted lists (cookies and children, boats and people) where pairing extremes is natural.
- Constraints around 10⁵ or more with no obvious DP state small enough to tabulate.
Proving a greedy algorithm correct
- 1
Fix an optimal solution
Let OPT be any optimal solution. If it already agrees with greedy's first choice, move on to the rest of the problem.
- 2
Find the first difference
Let g be greedy's choice and o be OPT's choice at the first point where they differ.
- 3
Exchange
Replace o with g in OPT. Show the result is still feasible (no new conflicts) and its cost is no worse.
- 4
Repeat
The modified OPT agrees with greedy on one more choice and is still optimal. By induction, greedy's full solution is optimal.
Activity selection (interval scheduling)
Given intervals, choose the maximum number that do not overlap. The greedy rule: sort by end time, then take each interval whose start is at or after the end of the last one taken. The visualization above runs exactly this: intervals are scanned by finish time, and each is either selected or rejected because it overlaps the last selection.
| Interval (sorted by end) | Last end | Decision |
|---|---|---|
| [1, 4) | −∞ | Take, last end = 4 |
| [3, 5) | 4 | Skip, starts before 4 |
| [0, 6) | 4 | Skip |
| [5, 7) | 4 | Take, last end = 7 |
| [3, 9), [5, 9), [6, 10) | 7 | Skip all three |
| [8, 11) | 7 | Take, last end = 11 |
| [8, 12), [2, 14) | 11 | Skip both |
| [12, 16) | 11 | Take: 4 intervals in total |
Earliest start first: wrong
[0, 10), [1, 2), [3, 4)- Picks
[0, 10)and nothing else: 1 - Optimal picks the two short ones: 2
Shortest first: wrong
[0, 5), [4, 7), [6, 11)- Picks
[4, 7), which blocks both others: 1 - Optimal:
[0, 5)and[6, 11): 2
Earliest end first: right
- Leaves the most room for the rest
- Provably optimal by exchange
- O(n log n) for the sort, then O(n)
Fractional knapsack
Items have value and weight, and you may take fractions of items. Sort by value per unit of weight, take whole items while they fit, then take the fraction of the next item that fills the bag. An exchange argument shows that swapping any weight from a lower-ratio item to a higher-ratio item never decreases value.
| Item | Value | Weight | Value / weight |
|---|---|---|---|
| A | 60 | 10 | 6 |
| B | 100 | 20 | 5 |
| C | 120 | 30 | 4 |
Huffman coding
Huffman coding builds an optimal prefix-free binary code: frequent symbols get short codewords, rare symbols get long ones. The greedy step: repeatedly merge the two least frequent nodes into a new node whose frequency is their sum, using a min-heap. With n symbols that is n − 1 merges, O(n log n).
- 1
Start
Frequencies: a 45, b 13, c 12, d 16, e 9, f 5 (thousands of characters).
- 2
Merge f + e
5 + 9 = 14.
- 3
Merge c + b
12 + 13 = 25.
- 4
Merge 14 + d
14 + 16 = 30.
- 5
Merge 25 + 30
= 55.
- 6
Merge a + 55
= 100, the root. Codes: a =
0, c =100, b =101, d =111, f =1100, e =1101.
Total cost is 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 224 thousand bits, versus 300 thousand for a fixed 3-bit code. The exchange argument: the two rarest symbols can always be swapped into sibling leaves at the deepest level without increasing cost.
import heapq
from itertools import count
def huffman_codes(freq: dict[str, int]) -> dict[str, str]:
tie = count() # tie-breaker so tuples never compare trees
heap = [(f, next(tie), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
return {heap[0][2]: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap) # two least frequent nodes
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tie), (left, right)))
codes: dict[str, str] = {}
def walk(node, prefix: str) -> None:
if isinstance(node, str):
codes[node] = prefix
else:
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
walk(heap[0][2], "")
return codesJump game and gas station
Jump game
Each nums[i] is the maximum jump length from index i. Track the farthest index reachable so far. If the loop ever reaches an index beyond that frontier, you are stuck. No need to explore individual jump choices: all that matters is the frontier. Jump Game II (minimum jumps) extends this into BFS-like levels: each jump covers the range [start, farthest] reachable with the current number of jumps.
Gas station
If total gas is less than total cost, no start works. Otherwise exactly one does (the problem guarantees uniqueness), and greedy finds it in one pass: keep a running tank; whenever it goes negative at station j, the start must be after j, so reset the tank and set start = j + 1.
When greedy fails: coin change
With US coins {1, 5, 10, 25}, "take the largest coin that fits" always gives the fewest coins. That is a property of this particular coin system (it is canonical), not of greedy in general.
| Coins {1, 3, 4}, amount 6 | Coins used | Count |
|---|---|---|
| Greedy (largest first) | 4 + 1 + 1 | 3 |
| Optimal | 3 + 3 | 2 |
dp[x] = 1 + min(dp[x - c]).Famous greedy algorithms on graphs
- Dijkstra's Algorithm: always settle the unsettled vertex with the smallest tentative distance. Greedy is safe because edge weights are non-negative; a single negative edge breaks the argument.
- Kruskal's Minimum Spanning Trees: add the cheapest edge that does not form a cycle, detected with Union-Find (Disjoint Set).
- Prim's MST: grow one tree by repeatedly adding the cheapest edge leaving it.
- The cut property is the exchange argument for both MST algorithms: the lightest edge crossing any cut belongs to some MST.
Greedy vs dynamic programming
Greedy
- Commits to one choice per step, never reconsiders
- Needs the greedy-choice property (prove it!)
- Usually O(n log n) and O(1) extra space
- Activity selection, Huffman, Dijkstra, MST
Dynamic programming
- Considers every choice and keeps the best per subproblem
- Needs only optimal substructure and overlapping subproblems
- Usually polynomial but heavier (tables of states)
- 0/1 knapsack, general coin change, edit distance
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Activity selection | O(n log n) | O(1) | Sort by end, one pass |
| Fractional knapsack | O(n log n) | O(1) | Sort by value/weight |
| Huffman coding | O(n log n) | O(n) | Min-heap, n − 1 merges |
| Jump game | O(n) | O(1) | Farthest reach |
| Gas station | O(n) | O(1) | Reset start on negative tank |
| Dijkstra (binary heap) | O((V + E) log V) | O(V) | Non-negative weights |
| Kruskal's MST | O(E log E) | O(V) | Sort edges + union-find |
Space excludes the input and assumes in-place sorting.
Implementation
Sort by end time and keep every interval that starts at or after the last selected end.
def select_activities(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
chosen: list[tuple[int, int]] = []
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]): # earliest end first
if start >= last_end: # compatible with everything chosen so far
chosen.append((start, end))
last_end = end
return chosenKey takeaways
- Greedy commits to the locally best choice and never reconsiders; it is correct only with the greedy-choice property and optimal substructure.
- Prove greedy with an exchange argument: swapping an optimal solution's choice for the greedy one never makes it worse.
- Interval scheduling sorts by end time; sorting by start or by length fails.
- Fractional knapsack and Huffman coding are greedy; 0/1 knapsack and general coin change are not.
- Dijkstra, Kruskal and Prim are greedy algorithms backed by exchange-style proofs.
Common pitfalls
- Trusting an intuitive rule without testing it against small counterexamples.
- Sorting intervals by start time when the problem needs end time (or vice versa for merging).
- Using greedy coin change on a non-canonical coin system.
- Confusing fractional and 0/1 knapsack.
- Using Dijkstra's greedy settling with negative edge weights.
Interview tips
- Say the greedy rule and the exchange argument in one or two sentences before coding.
- Offer a counterexample for a wrong rule; it shows you understand why the right one works.
- If a greedy proof will not come, fall back to DP and mention the trade-off in complexity.
Real-world applications
- Compression formats (DEFLATE in ZIP, gzip and PNG uses Huffman coding).
- CPU and meeting-room scheduling, job sequencing with deadlines.
- Network routing (shortest paths) and network design (spanning trees).
- Change-making in vending machines and cash registers with canonical coin systems.
Practice problems
Test yourself
For activity selection (maximum number of non-overlapping intervals), what should you sort by?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.