Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

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 [s,f)[s, f) as possible, the key is the finish time:

python
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 chosen

O(nlog⁡n)O(n \log n) worst case for the sort, then O(n)O(n) 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.

DerivationProof by induction on r
  1. f(g1) ≤ f(o1)f(g_1)\ \le\ f(o_1)

    Base. Greedy's first pick has the earliest finish time of all the intervals:

  2. s(or) ≥ f(or−1) ≥ f(gr−1)s(o_r)\ \ge\ f(o_{r-1})\ \ge\ f(g_{r-1})

    Step. Suppose f(gr−1)≤f(or−1)f(g_{r-1}) \le f(o_{r-1}). The other schedule's next interval starts after its previous one ends, hence after greedy's previous pick ends too:

  3. f(gr) ≤ f(or)f(g_r)\ \le\ f(o_r)

    So oro_r is still available when greedy makes its rr-th pick, and greedy takes the available interval that finishes first:

  4. k ≥ mk\ \ge\ m

    Conclusion. If m>km > k, then ok+1o_{k+1} starts after f(ok)≥f(gk)f(o_k) \ge f(g_k), 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 nn jobs, one at a time and with no gaps. Job jj takes tjt_j time units and has a deadline djd_j. If it finishes at time CjC_j, its lateness is ℓj=max⁡(0, Cj−dj)\ell_j = \max(0,\ C_j - d_j). The goal is to minimize the maximum lateness L=max⁡jℓjL = \max_j \ell_j (Kleinberg & Tardos, §4.2). Three keys suggest themselves, and two of them fail on two-job instances:

KeyJobs (t,d)(t, d)What happens
Shortest job first(1,100)(1, 100), (10,10)(10, 10)the long job ends at 11: L=1L = 1, while deadline order gives L=0L = 0
Least slack dj−tjd_j - t_j first(1,2)(1, 2), (10,10)(10, 10)the long job (slack 0) runs first and the short one ends at 11: L=9L = 9, while deadline order gives L=1L = 1
Earliest deadline first (EDF)anyoptimal, as proved below
On the four jobs A (1,1)(1, 1), B (4,3)(4, 3), C (2,6)(2, 6), D (3,10)(3, 10), shortest first gives L=7L = 7, least slack first L=4L = 4, and EDF L=2L = 2, the optimum.

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.

DerivationProof: an adjacent swap never hurts
  1. ℓj=max⁡(0, C−dj)\ell_j = \max(0,\ C - d_j)

    Let job ii run immediately before job jj with di>djd_i > d_j, and let CC be the time at which the second of the two finishes. Before the swap, jj finishes at CC:

  2. ℓi′=max⁡(0, C−di) ≤ max⁡(0, C−dj)=ℓj\ell'_i = \max(0,\ C - d_i)\ \le\ \max(0,\ C - d_j) = \ell_j

    After swapping the two, jj finishes earlier, so its lateness cannot grow, and ii now finishes at CC. Every other job keeps its finish time. Because di>djd_i > d_j:

  3. L(after swap) ≤ L(before swap)L(\text{after swap})\ \le\ L(\text{before swap})

    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:

  4. L(EDF) = L(OPT)L(\text{EDF})\ =\ L(\text{OPT})

    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:

python
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, worst
Predict before you look

Four jobs (t,d)(t, d): (2,3)(2, 3), (1,4)(1, 4), (3,5)(3, 5), (2,9)(2, 9). What maximum lateness does EDF achieve?

Show the answer

1

Deadline order is the listed order. The finish times are 2,3,6,82, 3, 6, 8 against deadlines 3,4,5,93, 4, 5, 9, so only the third job is late, by 6−5=16 - 5 = 1. No order can do better: the three jobs with deadlines at most 5 need 2+1+3=62 + 1 + 3 = 6 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.

python
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)

O(nlog⁡n)O(n \log n) worst case. When greedy opens room number kk for a lecture starting at ss, the other k−1k - 1 rooms are busy at time ss with lectures that started no later, so kk lectures contain the point ss and the depth is at least kk. Greedy never uses more rooms than the depth, and nothing can use fewer.

Check your understanding

Lectures [9,11)[9,11), [9,10)[9,10), [10,12)[10,12), [11,13)[11,13), [12,13)[12,13) and [10,11)[10,11), all half-open. How many rooms are needed?

  1. 2
  2. 3
  3. 4
  4. 6
Show the answer

B. 3

At time 10, three lectures are running: [9,11)[9,11), [10,12)[10,12) and [10,11)[10,11). At every other start time at most two are. The depth is 3, and greedy uses exactly 3 rooms.

Fractional knapsack. Items have weights wiw_i and values viv_i, the bag holds weight WW, and you may take any fraction of an item. Sort by value per unit of weight vi/wiv_i / w_i, take whole items while they fit, then the fraction of the next item that fills the bag: O(nlog⁡n)O(n \log n). 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 4+1+14 + 1 + 1 instead of 3+33 + 3.
  • Longest paths: always following the heaviest edge can walk into a dead end. With edges s→as \to a (1), s→bs \to b (2), a→ta \to t (10) and b→tb \to t (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 O(nlog⁡n)O(n \log n).
Check your understanding

For the coins 1, 5, 10 and 25, greedy always pays with the fewest coins. Suppose a 20-cent coin is added. What happens?

  1. Greedy stays optimal: an extra coin can only make paying easier
  2. Greedy now loses on every amount above 20
  3. Greedy now loses on some amounts, for example 40
  4. 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 25+10+525 + 10 + 5, three coins, while 20+2020 + 20 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.

python
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))
        break

In our run this stopped at the 16th random instance and printed 16 [(9, 14), (3, 8), (6, 10)] 1 2: shortest first keeps only [6,10)[6, 10), which overlaps both others, while [3,8)[3, 8) and [9,14)[9, 14) 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 nn up to 10510^5 or 10610^6 point to O(nlog⁡n)O(n \log n): 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 ideaWhy it worksTime
Jump game: from index ii you may jump up to a[i]a[i] positions forward. Can you reach the last index?Keep the farthest reachable index, far=max⁡(far, i+a[i])far = \max(far,\ i + a[i]); fail as soon as i>fari > far.Stays ahead: farfar is exactly the farthest index reachable from positions up to ii.O(n)O(n)
Gas station: a circular route, gas gig_i at station ii, cost cic_i to reach the next. Where can you start?If ∑g<∑c\sum g < \sum c, nowhere. Otherwise restart just after every point where the tank goes negative.If you run dry between ii and jj, every start in [i,j][i, j] runs dry too.O(n)O(n)
Assign cookies: children need sizes gig_i, cookies have sizes sjs_j; 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.O(nlog⁡n)O(n \log n)
Balloons and arrows: the fewest points that hit every closed interval [a,b][a, b].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.O(nlog⁡n)O(n \log n)
Cooldown scheduling: NN tasks, equal tasks at least k+1k + 1 slots apart; the fewest slots.With cc the largest count and tt the number of tasks that have it: max⁡(N, (c−1)(k+1)+t)\max\big(N,\ (c - 1)(k + 1) + t\big).The most frequent task forces c−1c - 1 full frames of length k+1k + 1; the other tasks fill gaps or remove the need for them.O(N)O(N)
Largest number: concatenate non-negative integers into the largest possible number.Sort the strings so that aa comes before bb when a+b>b+aa + b > b + a (as strings).Adjacent-swap exchange; the comparator is transitive (proved in the Optimal lesson).O(nlog⁡n)O(n \log n) comparisons
For example, tasks AAABBC with k=2k = 2 need max⁡(6, 2⋅3+1)=7\max(6,\ 2 \cdot 3 + 1) = 7 slots: A B C A B (idle) A. For the numbers 3, 30, 34, 5, 9 the comparator gives 9534330; sorting the strings in plain reverse alphabetical order gives 9534303, because "30" sorts before "3" although 330>303330 > 303.

Greedy across the course

Several of the most important algorithms in this course are greedy, each with its own proof of the greedy choice:

AlgorithmGreedy choiceWhy it is safe
Kruskal (minimum spanning tree)the lightest edge that joins two different componentsthe cut property: the lightest edge across any cut belongs to some minimum spanning tree
Primthe lightest edge leaving the tree grown so farthe cut property, for the cut between the tree and the rest
Dijkstra (shortest paths)settle the unsettled vertex with the smallest distance estimatestays ahead, but only with non-negative edge weights
Huffman (optimal prefix codes)merge the two least frequent symbolsan exchange argument plus a reduction to one fewer symbol
Greedy set coverthe set that covers the most uncovered elementsnot optimal, but within a factor of about ln⁡n\ln n of the optimum
Minimum spanning trees are in Minimum Spanning Trees & Union-Find, Dijkstra in Shortest Paths, and set cover in Approximation Algorithms.

Key takeaways

  • A greedy algorithm sorts by a key and commits to each compatible item in one scan, usually in O(nlog⁡n)O(n \log n) 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.

Question 1

In the exchange argument for EDF, job ii runs just before job jj and di>djd_i > d_j. Why does swapping them never increase the maximum lateness?

  1. Both jobs finish earlier after the swap
  2. After the swap, ii finishes when jj used to, and di>djd_i > d_j makes ii's new lateness at most jj's old lateness
  3. The swap shortens the total length of the schedule
  4. Lateness depends only on the order of the deadlines, not on finish times
Show the answer

B. After the swap, ii finishes when jj used to, and di>djd_i > d_j makes ii's new lateness at most jj's old lateness

Only ii and jj change finish times. jj moves earlier, so its lateness cannot grow. ii takes over jj's old finish time CC, and C−di<C−djC - d_i < C - d_j, so ii's new lateness is at most jj's old one. The maximum over all jobs cannot increase.

Question 2

Which statement about the fractional and the 0/1 knapsack is true?

  1. Rounding down the fractional greedy's answer gives the 0/1 optimum
  2. Sorting by value instead of value per weight makes greedy optimal for 0/1
  3. The fractional greedy's value is an upper bound on the value of every 0/1 packing
  4. 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.

Question 3

Which of these problems is solved exactly by a greedy algorithm?

  1. Choose non-overlapping intervals with the largest total value
  2. Pay an amount with the fewest coins, for an arbitrary coin system
  3. Choose whole items of the largest total value under a weight limit
  4. 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.

Question 4

Running the interval-partitioning greedy, you see it open a fourth room for a lecture that starts at time ss. What does that prove?

  1. The greedy made a poor choice earlier, which a smarter assignment would avoid
  2. Four lectures are in progress at time ss, so every valid assignment needs at least four rooms
  3. The optimum is exactly four rooms
  4. Nothing, until the algorithm finishes
Show the answer

B. Four lectures are in progress at time ss, so every valid assignment needs at least four rooms

Greedy opens a room only when every open room is busy at time ss, with lectures that started at or before ss and end after it. Together with the new lecture, four lectures contain the point ss: the depth is at least 4, a lower bound for any assignment.

Go deeper

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.