Greedy algorithms
A greedy algorithm takes the best-looking choice at every step and never goes back; it is fast but only sometimes right: coins of 1, 5, 10 and 25 make change correctly, while 1, 3 and 4 make 6 with three coins instead of two.
A cashier gives 63 cents in change from 25, 10, 5 and 1 cent coins. They do not think through every combination; each time they take the largest coin that still fits: 25, 25, 10, 1, 1, 1, six coins, which happens to be the fewest. That is a greedy algorithm: at every step make the choice that looks best right now, and never change it. It is far faster than backtracking (which tries every option; greedy follows a single path), but it is not always right: with coins of 1, 3 and 4 cents, making 6 cents, greedy gives 4 + 1 + 1, three coins, when 3 + 3, two coins, would do. This lesson looks at where greedy is right, where it is wrong, and how to show that it is right.
Take the largest each time
Greedy change: sort the coins from largest down, and keep taking each kind while it fits, until what is left is smaller than it.
| Left | Largest coin that fits | Left after |
|---|---|---|
| 63 | 25 | 38 |
| 38 | 25 | 13 |
| 13 | 10 | 3 |
| 3 | 1 | 2 |
| 2 | 1 | 1 |
| 1 | 1 | 0 |
1def greedy_change(coins, amount):2 taken = []3 for c in sorted(coins, reverse=True): # largest first4 while amount >= c:5 amount -= c6 taken.append(c)7 return taken8 9print(greedy_change([1, 5, 10, 25], 63))10print(greedy_change([1, 5, 10, 25], 99))11print(greedy_change([1, 3, 4], 6))
[25, 25, 10, 1, 1, 1] [25, 25, 25, 10, 10, 1, 1, 1, 1] [4, 1, 1]
Make change again with a different set of coins:
The coins are 1, 3 and 4; greedy makes 10. What does it print?
1def greedy_change(coins, amount):2 taken = []3 for c in sorted(coins, reverse=True):4 while amount >= c:5 amount -= c6 taken.append(c)7 return taken8 9print(greedy_change([1, 3, 4], 10))
[4, 4, 2] is impossible, as there is no 2-cent coin.4 + 1 + 13 coinsafter the 4, the remaining 2 needs two 1s3 + 32 coinsa "smaller" 3 first saves a coin laterHow often is it wrong? Compare every amount from 1 to 20 with the fewest coins found by "trying every way":
1def greedy_change(coins, amount):2 taken = []3 for c in sorted(coins, reverse=True):4 while amount >= c:5 amount -= c6 taken.append(c)7 return taken8 9def fewest_134(amount): # 1, 3, 4: try every count of 4s and of 3s, fill the rest with 1s10 best = amount11 for a in range(amount // 4 + 1):12 for b in range((amount - 4 * a) // 3 + 1):13 n = a + b + (amount - 4 * a - 3 * b)14 best = min(best, n)15 return best16 17wrong = [m for m in range(1, 21) if len(greedy_change([1, 3, 4], m)) != fewest_134(m)]18print("amounts where greedy uses extra coins:", wrong)
amounts where greedy uses extra coins: [6, 10, 14, 18]
The 1, 5, 10, 25 set was designed on purpose: greedy gives the fewest coins for every amount (you can check them one by one the same way). With 1, 3, 4 it does not: below 20, it is wrong for 6, 10, 14 and 18. The fewest coins for change generally needs dynamic programming (lesson 5); greedy is only right for particular coin sets.
The coins are 1, 5, 6 and 9, and you need to make 11. How many coins does greedy use? How few will do?
Fill in the comparison in the while: keep taking this coin as long as there is enough for it. The program should print 6 (63 = 25 + 25 + 10 + 1 + 1 + 1).
1def greedy_change(coins, amount):2 taken = []3 for c in sorted(coins, reverse=True):4 while amount c:5 amount -= c6 taken.append(c)7 return taken8 9print(len(greedy_change([1, 5, 10, 25], 63)))
>=. With >, the last 1 can't be taken when 1 is left, and it prints 5; with <=, no coin is ever taken.Interval scheduling: earliest end first
One meeting room, 8 meetings, each with a start and end time [s, e) (the end moment itself is free, so the next can start right then). How many can you fit in?
There are several candidates for "best right now": the earliest start, the shortest, the earliest end. Only the last is right. The intuition: the earlier a meeting ends, the more time it leaves for the rest. Sort by end time, scan from the front, and take each meeting that does not clash with those already taken.
sorted's key= decides what to sort by. The same code with three keys is three different greedy algorithms:
1meetings = [("A", 0, 10), ("B", 1, 4), ("C", 4, 7), ("D", 3, 5),2 ("E", 7, 10), ("F", 6, 8), ("G", 10, 12), ("H", 9, 11)]3 4def schedule(meetings, key):5 chosen, end = [], 06 for name, s, e in sorted(meetings, key=key):7 if s >= end: # no earlier than the last chosen one ends8 chosen.append(name)9 end = e10 return chosen11 12print("earliest end: ", schedule(meetings, key=lambda m: m[2]))13print("earliest start:", schedule(meetings, key=lambda m: m[1]))14print("shortest first:", schedule(meetings, key=lambda m: m[2] - m[1]))
earliest end: ['B', 'C', 'E', 'G'] earliest start: ['A', 'G'] shortest first: ['D', 'F', 'G']
Earliest start picks A first (0 to 10), one long meeting filling the morning, and fits only 2; shortest first picks D, F and G, 3 in all: D is short, but it sits right between B and C and blocks both. Only earliest end fits 4.
5 meetings: A [1, 3), B [2, 5), C [3, 6), D [5, 7), E [6, 9). Picking by "earliest finish", which ones are chosen?
n meetings: sort them by end time, then sweep once from the start (each one compared only with the last one taken). What is the whole algorithm's time complexity?
Handing out cookies
✓Each child has an appetite g[i] and each cookie a size s[j]; a child is content when the cookie's size is at least their appetite, and each cookie goes to one child. Complete content(g, s): the most children that can be content. Greedy: sort both, and offer the smallest cookie to the least hungry child first.
1 2 3
1def content(g, s):2 g, s = sorted(g), sorted(s)3 i = 0 # the next child waiting for a cookie4 # look at the cookies from smallest up: if one satisfies g[i], give it, i += 1; otherwise throw it away5 return i6 7print(content([1, 2, 3], [1, 1]))8print(content([1, 2], [1, 2, 3]))9print(content([3, 1, 4], [2, 5, 1, 3]))
Why "best at each step" needs proof
Greedy code is always short; the hard part is whether it is right. All three greedy choices in the previous stage "make sense", yet only one is right. The usual way to show a greedy choice is right is an exchange argument:
- Take any optimal schedule O, whose first meeting is X; greedy's first is B, the meeting that ends earliest of all, so B ends no later than X.
- Swap X for B in O: B ends no later than X, and the rest of O started after X ended, so also after B ends; nothing clashes. It is still a valid schedule with the same number of meetings, still optimal.
- So "take B first" loses nothing. Remove B and everything that clashes with it, and what remains is a smaller problem of the same kind; apply the same argument again.
The other way round, to show a greedy choice is wrong you need one counterexample: coins 1, 3, 4 making 6; meeting A, running from 0 to 10, which leaves "earliest start" with only 2.
| Problem | Greedy choice | Right? |
|---|---|---|
| Interval scheduling (most non-overlapping) | earliest end first | yes, by exchange argument |
| Change (1, 5, 10, 25) | largest coin each time | yes (for this coin set) |
| Change (any coins) | largest coin each time | no: dynamic programming |
| Jump game | remember the farthest reachable | yes |
| Huffman coding (chapter 4) | merge the two smallest | yes |
| Dijkstra, Prim, Kruskal (chapter 5) | the nearest vertex, the shortest edge | yes (no negative weights) |
| 0-1 knapsack | highest value per weight first | no: dynamic programming |
In interviews: before writing a greedy algorithm, say "why choosing this way at each step loses nothing", even if it is a one-line exchange argument; then offer an example where another greedy choice fails (the long meeting that starts first). What the interviewer most wants to hear is that you know greedy can be wrong and how to check it.
In the exchange argument, the first meeting X of a best schedule is swapped for B (the meeting that ends earliest of all). Why can't the swap clash with the meetings after it?
Three meetings: [0, 5), [4, 7), [6, 10). Picking "shortest first", how many do you get? And how many could you actually fit?
Which of these is not a greedy algorithm?
Jump game
nums[i] is the farthest you can jump forward from index i. Starting at index 0, can you reach the last index?
Backtracking could try every way of jumping, but there is no need: just remember the farthest reachable index (far). Walk left to right; at i, if i > far, then i cannot be reached, and nothing beyond it can either; otherwise update far with i + nums[i]. One O(n) pass.
1def can_jump(nums):2 far = 03 for i, x in enumerate(nums):4 if i > far: # cannot even reach i5 return False6 far = max(far, i + x)7 return True8 9print(can_jump([2, 3, 1, 1, 4]))10print(can_jump([3, 2, 1, 0, 4])) # however you jump, you land on the 0 at index 311print(can_jump([0]))
True False True
Why it cannot go wrong: if you can reach i, you can reach every index before i, so "the reachable places" always form one stretch starting at 0, and only its right end, far, needs remembering.
Two lists: can you jump from index 0 to the last one? What does it print?
1def can_jump(nums):2 far = 03 for i, x in enumerate(nums):4 if i > far:5 return False6 far = max(far, i + x)7 return True8 9print(can_jump([2, 0, 0]), can_jump([1, 0, 2]))
[2, 0, 0]: from index 0 you can jump 2, far = 2, straight to the end: True. [1, 0, 2]: index 0 only reaches index 1, which holds 0, so far stays at 1; at index 2, 2 > far, unreachable: False. However big that last 2 is, it doesn't help.The fewest jumps
✓As in the jump game, nums[i] is the farthest you can jump from index i, and the last index can always be reached. Complete min_jumps(nums): the fewest jumps. Greedy: treat "the range reachable in k jumps" as a stretch; when you walk off its end, jump once, and the next stretch ends at the largest i + nums[i] inside this one.
2 2 3 0
1def min_jumps(nums):2 jumps = 03 end = 0 # the farthest this jump reaches4 far = 0 # the farthest one more jump could reach5 for i in range(len(nums) - 1):6 # update far; on reaching end you must jump again: jumps += 1, end = far7 pass8 return jumps9 10print(min_jumps([2, 3, 1, 1, 4]))11print(min_jumps([2, 3, 0, 1, 4]))12print(min_jumps([1, 1, 1, 1]))13print(min_jumps([0]))
How you write it at work
Greedy algorithms are nearly always sort, then one scan: the sorting is sorted(..., key=...), O(n log n). When it is "take the smallest or the largest each time" and the set keeps changing, use heapq. For example, when one room is not enough, how many rooms are needed at least: sort by start time and keep each room's end time in a heap; if the room that frees up first (the top of the heap) is free in time, reuse it, otherwise open another.
1import heapq2 3meetings = [("A", 0, 10), ("B", 1, 4), ("C", 4, 7), ("D", 3, 5),4 ("E", 7, 10), ("F", 6, 8), ("G", 10, 12), ("H", 9, 11)]5 6def min_rooms(meetings):7 ends = [] # when each room is free again8 for name, s, e in sorted(meetings, key=lambda m: m[1]):9 if ends and ends[0] <= s:10 heapq.heapreplace(ends, e) # the earliest free room is free in time: reuse it11 else:12 heapq.heappush(ends, e) # none free: open another room13 return len(ends)14 15print(min_rooms(meetings))16print(sorted(meetings, key=lambda m: (m[2], m[1]))[:3])17print(max(meetings, key=lambda m: m[2] - m[1]))
3
[('B', 1, 4), ('D', 3, 5), ('C', 4, 7)]
('A', 0, 10)
key=lambda m: m[2]sorts by the third field;key=lambda m: (m[2], m[1])by end, then by start when ends are equal.sortedis stable: equal keys keep their original order.max(xs, key=...)andmin(xs, key=...)find "the best one" in one O(n) pass.heapq.heapreplace(h, x)pops the smallest and then pushes x, one adjustment fewer thanheappopplusheappush.- Look for a counterexample first: comparing a few small cases with brute force (backtracking) is the quickest check on a greedy algorithm.
Three meetings: how many meeting rooms are needed at least?
1import heapq2 3def min_rooms(meetings):4 ends = []5 for name, s, e in sorted(meetings, key=lambda m: m[1]):6 if ends and ends[0] <= s:7 heapq.heapreplace(ends, e)8 else:9 heapq.heappush(ends, e)10 return len(ends)11 12print(min_rooms([("A", 0, 30), ("B", 5, 10), ("C", 15, 20)]))
Summary
Greedy: the best-looking choice at each step
- One path, never looking back: usually an O(n log n) sort plus one scan
- Not always right: coins 1, 3, 4 making 6, greedy uses 3, the fewest is 2
- Interval scheduling: earliest end first; earliest start and shortest first have counterexamples
- To show it is right: an exchange argument; to show it is wrong: one counterexample
1chosen, end = [], 02for name, s, e in sorted(meetings, key=lambda m: m[2]):3 if s >= end:4 chosen.append(name)5 end = e