Greedy Algorithms
Take the best-looking step and never look back, and prove when that works.
Kruskal's spanning trees, Dijkstra's shortest paths, Huffman's codes and the scheduler that keeps the most meetings are all greedy: one locally best choice after another, never revised. Each fits in a few lines of code. The hard part is knowing that it is right, and a plausible greedy that is subtly wrong is one of the classic traps of interviews and contests.
What you’ll learn
- Write a greedy algorithm as "sort by a key, then scan once and commit", and state its exact running time.
- Prove a greedy algorithm optimal with "greedy stays ahead" (interval scheduling) and with an exchange argument (minimizing the maximum lateness).
- Solve interval partitioning, fractional knapsack and the classic contest greedies, each with its proof idea.
- Refute a wrong greedy quickly by stress-testing it against a brute force on small random inputs.
- Recognize greedy problems from their statements, and the look-alikes that need dynamic programming instead.
Interval scheduling: greedy stays ahead
Almost every greedy algorithm in this lesson has one skeleton: sort the items by a key, then scan them once, committing to each item that is still compatible with what you kept. Choosing the key is the design; proving it is the work.
For interval scheduling, keeping as many pairwise disjoint half-open intervals as possible, the key is the finish time:
def max_meetings(intervals): # half-open [s, f)
chosen, free_at = [], float('-inf')
for s, f in sorted(intervals, key=lambda iv: iv[1]): # earliest finish first
if s >= free_at: # starts after the last kept meeting ends
chosen.append((s, f))
free_at = f
return chosenworst case for the sort, then for the scan. Comparing with the last kept interval is enough: it has the latest finish of all kept intervals, because they were taken in order of finish time.
Base. Greedy's first pick has the earliest finish time of all the intervals:
Step. Suppose . The other schedule's next interval starts after its previous one ends, hence after greedy's previous pick ends too:
So is still available when greedy makes its -th pick, and greedy takes the available interval that finishes first:
Conclusion. If , then starts after , so it was still available after greedy's last pick, and greedy would not have stopped. Hence greedy keeps at least as many intervals as any schedule:
The template is general: define a measure of progress (here, how early the room is free again), prove by induction that greedy is never behind after any number of steps, and conclude that it cannot finish behind. Other plausible keys fail exactly because no such measure exists for them.
Exchange arguments: minimizing lateness
One machine must run jobs, one at a time and with no gaps. Job takes time units and has a deadline . If it finishes at time , its lateness is . The goal is to minimize the maximum lateness (Kleinberg & Tardos, §4.2). Three keys suggest themselves, and two of them fail on two-job instances:
| Key | Jobs | What happens |
|---|---|---|
| Shortest job first | , | the long job ends at 11: , while deadline order gives |
| Least slack first | , | the long job (slack 0) runs first and the short one ends at 11: , while deadline order gives |
| Earliest deadline first (EDF) | any | optimal, as proved below |
An exchange argument proves optimality differently from staying ahead: take any optimal solution and transform it, one small step at a time, into the greedy solution without ever making it worse. Here the steps are swaps. An inversion is a pair of jobs in which the one with the later deadline runs first. EDF has no inversions, and a schedule with an inversion always has two adjacent inverted jobs.
Let job run immediately before job with , and let be the time at which the second of the two finishes. Before the swap, finishes at :
After swapping the two, finishes earlier, so its lateness cannot grow, and now finishes at . Every other job keeps its finish time. Because :
So the maximum lateness does not increase. Each swap removes exactly one inversion, so an optimal schedule can be turned into one with no inversions while staying optimal:
Schedules with no inversions and no idle time differ only in the order of jobs with equal deadlines. Those jobs form one block that ends at the same time in every such schedule, so all these schedules have the same maximum lateness. EDF is one of them:
def edf(jobs): # jobs: list of (t, d)
order = sorted(range(len(jobs)), key=lambda j: jobs[j][1])
time = worst = 0
for j in order:
time += jobs[j][0]
worst = max(worst, time - jobs[j][1]) # lateness is never negative
return order, worstFour jobs : , , , . What maximum lateness does EDF achieve?
Show the answer
1
Deadline order is the listed order. The finish times are against deadlines , so only the third job is late, by . No order can do better: the three jobs with deadlines at most 5 need time units, so one of them finishes at time 6 or later.
Rooms and fractions: two more greedy proofs
Interval partitioning. Now every lecture must take place, and you want the fewest rooms. The depth of the lectures, the largest number of them that contain a common point in time, is an obvious lower bound: those lectures need pairwise different rooms. A greedy algorithm meets that bound exactly.
import heapq
def min_rooms(intervals): # half-open [s, f)
free = [] # min-heap of end times of rooms in use
for s, f in sorted(intervals): # by start time
if free and free[0] <= s:
heapq.heapreplace(free, f) # reuse the room that frees up first
else:
heapq.heappush(free, f) # every room is busy: open a new one
return len(free)worst case. When greedy opens room number for a lecture starting at , the other rooms are busy at time with lectures that started no later, so lectures contain the point and the depth is at least . Greedy never uses more rooms than the depth, and nothing can use fewer.
Lectures , , , , and , all half-open. How many rooms are needed?
- 2
- 3
- 4
- 6
Show the answer
B. 3
At time 10, three lectures are running: , and . At every other start time at most two are. The depth is 3, and greedy uses exactly 3 rooms.
Fractional knapsack. Items have weights and values , the bag holds weight , and you may take any fraction of an item. Sort by value per unit of weight , take whole items while they fit, then the fraction of the next item that fills the bag: . An exchange argument proves it. If an optimal load holds less of a higher-ratio item and more of a lower-ratio one, moving weight from the lower-ratio item to the higher-ratio one raises the value, so an optimal load agrees with greedy's. With whole items only, the 0/1 knapsack, the same greedy fails:
When greedy fails, and how to catch it
Greedy fails whenever an early choice can block a better combination later. The classic failures:
- 0/1 knapsack: the item with the best ratio can waste capacity, as above.
- Coin systems that are not canonical: with coins 1, 3 and 4, greedy pays 6 as instead of .
- Longest paths: always following the heaviest edge can walk into a dead end. With edges (1), (2), (10) and (1), greedy finds a path of weight 3; the longest has weight 11.
- Weighted interval scheduling: once intervals carry values, earliest finish ignores them. Sorting by finish time and deciding "take it or skip it" by dynamic programming, with binary search for the last compatible interval, solves it in .
For the coins 1, 5, 10 and 25, greedy always pays with the fewest coins. Suppose a 20-cent coin is added. What happens?
- Greedy stays optimal: an extra coin can only make paying easier
- Greedy now loses on every amount above 20
- Greedy now loses on some amounts, for example 40
- Greedy stays optimal, because 20 is a multiple of 5 and of 10
Show the answer
C. Greedy now loses on some amounts, for example 40
Greedy pays 40 as , three coins, while needs two. Adding a coin can destroy canonicity: from 1 to 99, greedy now loses on the 15 amounts 40–44, 65–69 and 90–94. The widget below lets you check.
To test a greedy you are unsure of, compare it with a brute force on thousands of small random inputs. Small inputs are where counterexamples live: they are cheap to brute-force, and the first failure is short enough to read and understand.
import random
from itertools import combinations
def brute(intervals): # the largest compatible subset, by trying all
for k in range(len(intervals), 0, -1):
for sub in combinations(sorted(intervals), k):
if all(a[1] <= b[0] for a, b in zip(sub, sub[1:])):
return k
return 0
def greedy(intervals, key): # scan in key order, keep what still fits
chosen = []
for s, f in sorted(intervals, key=key):
if all(f <= cs or cf <= s for cs, cf in chosen):
chosen.append((s, f))
return len(chosen)
shortest = lambda iv: (iv[1] - iv[0], iv[0]) # shortest first, ties by start
random.seed(1)
for trial in range(1, 100001):
ivs = []
for _ in range(random.randint(1, 6)):
s = random.randint(0, 10)
ivs.append((s, s + random.randint(1, 5)))
if greedy(ivs, shortest) != brute(ivs):
print(trial, ivs, greedy(ivs, shortest), brute(ivs))
breakIn our run this stopped at the 16th random instance and printed 16 [(9, 14), (3, 8), (6, 10)] 1 2: shortest first keeps only , which overlaps both others, while and fit together. Swap in your own greedy and brute force, and the same harness tests any greedy idea in a few seconds.
Recognizing it
Signals. The answer is a set or an order built from the input's items. The statement asks for the maximum number of compatible items, the minimum number of resources (rooms, arrows, platforms, jumps), or the best order of jobs, and a natural key suggests itself: end time, deadline, ratio, size. Constraints of up to or point to : sort, then scan.
Before coding, try to break your key with an example of two or three items; then prove it with stays-ahead or an exchange argument, or stress-test it.
| Problem (in our words) | Greedy idea | Why it works | Time |
|---|---|---|---|
| Jump game: from index you may jump up to positions forward. Can you reach the last index? | Keep the farthest reachable index, ; fail as soon as . | Stays ahead: is exactly the farthest index reachable from positions up to . | |
| Gas station: a circular route, gas at station , cost to reach the next. Where can you start? | If , nowhere. Otherwise restart just after every point where the tank goes negative. | If you run dry between and , every start in runs dry too. | |
| Assign cookies: children need sizes , cookies have sizes ; feed as many children as possible. | Sort both; give each cookie, smallest first, to the least demanding unfed child it satisfies. | Exchange: some optimal pairing gives the smallest useful cookie to the least demanding child. | |
| Balloons and arrows: the fewest points that hit every closed interval . | Sort by right end; shoot at the right end of the first balloon not yet burst. | The stays-ahead proof of interval scheduling; the answer is the maximum number of disjoint balloons. | |
| Cooldown scheduling: tasks, equal tasks at least slots apart; the fewest slots. | With the largest count and the number of tasks that have it: . | The most frequent task forces full frames of length ; the other tasks fill gaps or remove the need for them. | |
| Largest number: concatenate non-negative integers into the largest possible number. | Sort the strings so that comes before when (as strings). | Adjacent-swap exchange; the comparator is transitive (proved in the Optimal lesson). | comparisons |
Greedy across the course
Several of the most important algorithms in this course are greedy, each with its own proof of the greedy choice:
| Algorithm | Greedy choice | Why it is safe |
|---|---|---|
| Kruskal (minimum spanning tree) | the lightest edge that joins two different components | the cut property: the lightest edge across any cut belongs to some minimum spanning tree |
| Prim | the lightest edge leaving the tree grown so far | the cut property, for the cut between the tree and the rest |
| Dijkstra (shortest paths) | settle the unsettled vertex with the smallest distance estimate | stays ahead, but only with non-negative edge weights |
| Huffman (optimal prefix codes) | merge the two least frequent symbols | an exchange argument plus a reduction to one fewer symbol |
| Greedy set cover | the set that covers the most uncovered elements | not optimal, but within a factor of about of the optimum |
Key takeaways
- A greedy algorithm sorts by a key and commits to each compatible item in one scan, usually in time: the key is the design, the proof is the work.
- "Greedy stays ahead" shows by induction that greedy is never behind any optimal solution (earliest finish for interval scheduling); an exchange argument turns an optimal solution into greedy's without making it worse (adjacent swaps for EDF).
- Interval partitioning meets the depth lower bound, and fractional knapsack is greedy by value per weight; the 0/1 knapsack, arbitrary coin systems and weighted intervals need dynamic programming.
- Before trusting a greedy, stress-test it against a brute force on small random inputs: counterexamples are usually tiny.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the exchange argument for EDF, job runs just before job and . Why does swapping them never increase the maximum lateness?
- Both jobs finish earlier after the swap
- After the swap, finishes when used to, and makes 's new lateness at most 's old lateness
- The swap shortens the total length of the schedule
- Lateness depends only on the order of the deadlines, not on finish times
Show the answer
B. After the swap, finishes when used to, and makes 's new lateness at most 's old lateness
Only and change finish times. moves earlier, so its lateness cannot grow. takes over 's old finish time , and , so 's new lateness is at most 's old one. The maximum over all jobs cannot increase.
Which statement about the fractional and the 0/1 knapsack is true?
- Rounding down the fractional greedy's answer gives the 0/1 optimum
- Sorting by value instead of value per weight makes greedy optimal for 0/1
- The fractional greedy's value is an upper bound on the value of every 0/1 packing
- The 0/1 greedy is optimal whenever all the weights are different
Show the answer
C. The fractional greedy's value is an upper bound on the value of every 0/1 packing
Every 0/1 packing is also a fractional packing (with fractions 0 and 1), and the fractional greedy is optimal among fractional packings, so its value bounds every 0/1 packing from above. That bound is exactly what branch-and-bound uses to prune knapsack searches.
Which of these problems is solved exactly by a greedy algorithm?
- Choose non-overlapping intervals with the largest total value
- Pay an amount with the fewest coins, for an arbitrary coin system
- Choose whole items of the largest total value under a weight limit
- Find the fewest points such that every closed interval contains at least one of them
Show the answer
D. Find the fewest points such that every closed interval contains at least one of them
This is interval stabbing ("burst the balloons with the fewest arrows"): sort by right end and place a point at the right end of the first interval not yet hit. The stays-ahead proof of interval scheduling carries over, and the answer equals the maximum number of disjoint intervals.
Running the interval-partitioning greedy, you see it open a fourth room for a lecture that starts at time . What does that prove?
- The greedy made a poor choice earlier, which a smarter assignment would avoid
- Four lectures are in progress at time , so every valid assignment needs at least four rooms
- The optimum is exactly four rooms
- Nothing, until the algorithm finishes
Show the answer
B. Four lectures are in progress at time , so every valid assignment needs at least four rooms
Greedy opens a room only when every open room is busy at time , with lectures that started at or before and end after it. Together with the new lecture, four lectures contain the point : the depth is at least 4, a lower bound for any assignment.
Go deeper
- Proving Greedy Algorithms Correct · Exchange arguments, “greedy stays ahead”, and finding counterexamples.
- Huffman Coding · Optimal prefix codes by repeatedly merging the two rarest symbols.
- Matroids & the Greedy Algorithm · The structure that makes greedy optimal: the Rado–Edmonds theorem.
Further reading
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 4: §4.1 interval scheduling and partitioning, §4.2 minimizing lateness.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 15.
- J. Erickson, Algorithms (2019), chapter 4.
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 6.