Lesson 28 of 40Advanced patterns
Greedy Algorithms
Recognise when taking the best-looking choice at each step is safe, prove it with an exchange or stays-ahead argument, and know when it fails.
A greedy algorithm makes the choice that looks best right now and never looks back. No table, no backtracking. When it works, it is usually the simplest and fastest solution there is: often a single pass, O(n).
The catch is the "when it works". Greedy feels right far more often than it is right, and interviewers know it. This lesson is about telling the two apart, how to argue a greedy rule is safe, and a handful of greedy algorithms you should be able to write from memory: Kadane's algorithm, the jump games, gas station, partition labels and candy.
A greedy choice that is safe
You have one meeting room and a list of meetings (start, end). Fit in as many as possible.
Some tempting rules: pick the shortest meeting first, or the one that starts earliest. The rule that works is: always pick the meeting that ends earliest (among those that do not clash with what you already picked).
Why is that safe? Here is the exchange argument, in plain words. Take any best schedule. Look at its first meeting. The earliest-ending meeting finishes no later than that one, so you can swap it in: it leaves at least as much room for everything after. The schedule is still valid and still has the same number of meetings. Repeat for the second meeting, the third, and so on. So the greedy choice is never worse than the best possible one.
That is the shape of every greedy proof: show that swapping the greedy choice into an optimal answer does not make it worse. If you cannot find such an argument, be suspicious.
When greedy fails: coin change
Making change with US coins (25, 10, 5, 1), the greedy rule "take the biggest coin that fits" gives the fewest coins. So it is tempting to think it always does.
Now use coins [1, 3, 4] and make 6:
| Strategy | Coins | Count |
|---|---|---|
| Greedy: biggest first | 4 + 1 + 1 | 3 |
| Best | 3 + 3 | 2 |
Taking the 4 looked great but forced two 1s afterwards. The exchange argument breaks: you cannot swap the 4 into the best answer 3 + 3 without making it worse. This is why coin change in general needs dynamic programming, which tries every "last coin". US coins happen to be designed so greedy works, but that is a property of those specific values.
What does this print?
def greedy_coins(coins, amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count
print(greedy_coins([1, 5, 6, 9], 11))Two ways to prove a greedy rule
You do not need a formal proof in an interview, but you do need a reason. There are two arguments that cover almost every greedy problem you will meet, and naming the one you are using sounds far stronger than "it works on the examples".
1. The exchange argument. You saw it with meetings. Take any optimal answer that disagrees with your greedy choice. Show that you can swap the greedy choice in without making the answer worse. Then some optimal answer agrees with greedy on the first choice, and by repeating the argument on what is left, on every choice. The shape is always: "suppose the best answer did X instead; replacing X with my choice keeps it valid and no worse".
Exchange arguments also tell you which key to sort by. For "schedule jobs to minimise total waiting time", compare two neighbouring jobs a and b. Running a first makes b wait a.time, and running b first makes a wait b.time. Swapping them only changes that one term, so the shorter job should go first. A sort key falls out of comparing just two neighbours. Non-overlapping Intervals in the Intervals lesson is the same argument as the meeting room here, with the answer counted as "removals" instead of "meetings kept".
2. Greedy stays ahead. Show that after every step, greedy's partial answer is at least as good as any other algorithm's partial answer after the same number of steps, measured by something that matters. If greedy is never behind at any step, it is not behind at the end. For meetings: after picking k meetings, greedy's k-th meeting ends no later than the k-th meeting of any valid schedule. So whenever another schedule can fit a (k + 1)-th meeting, greedy can too. Jump game's reach is a stays-ahead argument as well: no sequence of jumps through indexes 0..i can reach past reach.
Use the exchange argument when the answer is a set or an order of items. Use stays ahead when greedy builds the answer step by step and you can name a measure of progress (end time, reach, fuel). And keep the third tool handy: a counterexample search. Before you prove anything, spend a minute trying to break the rule on inputs of size 2 or 3. In the code below, every new greedy solution is checked against a brute force on thousands of random small inputs. That is how you build confidence in a greedy rule at your desk, and it is a habit worth bringing to work too.
Kadane's algorithm: maximum subarray
Find the largest sum of any contiguous subarray. Checking every subarray is O(n²). Kadane's algorithm does it in one pass with a greedy rule:
At each number, decide: extend the current subarray, or start fresh here. If the running sum so far is negative, it can only drag the new number down, so drop it. That is cur = max(x, cur + x). Track the best cur ever seen.
Start with the first number: cur = best = -2.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.O(n) time, O(1) space. Notice the start: cur = best = nums[0], not 0. Starting at 0 returns 0 for an all-negative array, which is wrong because the subarray must contain at least one number.
Kadane is also a tiny DP: cur is "the best subarray ending at i". Greedy and DP overlap more than textbooks suggest; greedy is the special case where you only ever need the single best previous choice.
Jump game
Each nums[i] is the farthest you can jump forward from index i. Starting at index 0, can you reach the last index?
Trying every jump sequence is exponential. The greedy insight: you do not care which jumps you take, only the farthest index reachable so far. Walk left to right. If the current index is beyond that reach, you are stuck. Otherwise, update reach = max(reach, i + nums[i]).
From index 0 we can reach up to index 3.
Press Run (⌘ Enter) to see what happens.Why is it safe? Any index up to reach is truly reachable (you got there through some sequence), and every index you can reach lies within that range. So the single number reach captures everything that matters.
Jump game II: fewest jumps, as BFS levels
Now you are told the end is reachable and asked for the minimum number of jumps. A DP over indexes works in O(n²). The greedy view is cleaner: think of it as breadth-first search over indexes, where level k is the set of indexes reachable in exactly k jumps. Because every index between 0 and reach is reachable, each level is a contiguous range, so you never need a queue. Two numbers describe it: level_end, the last index of the current level, and farthest, the furthest index the next level reaches.
Level 0 is just index 0. From it, farthest = 0 + 2 = 2.
Press Run (⌘ Enter) to see what happens.The loop runs to len(nums) - 1, not len(nums). If it visited the last index and that index happened to be a level_end, it would count one jump too many. O(n) time, O(1) space.
Gas station: one pass with a reset
Stations sit on a circle. Station i gives gas[i] fuel, and driving to the next station costs cost[i]. Find the start station from which you can drive all the way round, or -1. Trying every start is O(n²).
Two facts make it O(n):
- If total gas is at least total cost, some start works. If it is less, none does.
- If you start at
sand first run dry on the way out of stationi, then no station betweensandican be the start either. Every station you passed was reached with a tank of zero or more, so starting there instead means arriving atiwith less fuel, not more. So jump the start toi + 1and reset the tank.
Start at 0. Station 0 gives 1 and costs 3, so the tank is -2. Stranded.
Press Run (⌘ Enter) to see what happens.Why is the survivor guaranteed to finish the wrap-around? The stretch before start has a negative sum (that is why each reset happened), and the total is non-negative, so the stretch from start to the end holds enough surplus to cover it. This is the same "drop a negative running sum" move as Kadane: a prefix that went negative can never help what follows.
Partition labels: cut at the last occurrence
Split a string into as many parts as possible so that each letter appears in at most one part. Return the part sizes.
Record the last index of every letter. Walk the string, and keep end, the furthest last-occurrence of any letter seen in the current part. The part cannot close before end, because some letter inside it appears again there. When i reaches end, nothing inside reaches further, so cut. Cutting as early as possible is the stays-ahead argument: any valid split must cut no earlier than greedy does, and greedy's early cuts leave the most room for more parts.
Press Run (⌘ Enter) to see what happens.O(n) time, and O(1) space for the alphabet. If you squint, each letter defines an interval from its first to its last index, and this is merging overlapping intervals (Intervals) without needing to sort, because you meet the intervals in order of their start.
What does this print?
last = {ch: i for i, ch in enumerate("abaccbdd")}
sizes, start, end = [], 0, 0
for i, ch in enumerate("abaccbdd"):
end = max(end, last[ch])
if i == end:
sizes.append(end - start + 1)
start = i + 1
print(sizes)Candy: two passes, one rule each
Children stand in a line with ratings. Each gets at least one candy, and a child with a higher rating than a neighbour must get more than that neighbour. Find the minimum total.
A single left-to-right pass can satisfy "more than my left neighbour", but a long decreasing run on the right breaks it: in [1, 3, 4, 5, 2], the child rated 5 needs more than the child rated 2 to its right, which a forward pass has not seen yet. The fix is to handle each constraint in its own pass:
- Left to right: if
ratings[i] > ratings[i - 1], givec[i - 1] + 1. - Right to left: if
ratings[i] > ratings[i + 1], make surec[i]is at leastc[i + 1] + 1, usingmaxso you keep what the first pass required.
Press Run (⌘ Enter) to see what happens.Each pass gives every child the smallest count its own rule allows, and the max combines the two rules without raising anyone further than needed. Equal ratings impose nothing, so [1, 2, 2] gives 1, 2, 1. The "two passes, one per direction" pattern returns elsewhere: Product of Array Except Self (Prefix Sums and Difference Arrays) and Trapping Rain Water both combine a left-to-right fact with a right-to-left fact at each index.
max(c[i], c[i + 1] + 1) instead of just c[i + 1] + 1?Does a simple greedy rule work?
Common mistakes:
- Trusting a greedy rule because it works on the examples. Always look for a counterexample first.
- Initialising Kadane with 0 instead of the first element.
- Sorting by the wrong key (start time or length instead of end time for meeting selection).
- In jump game, checking
i > reachafter updating reach, which hides the stuck case. - In jump game II, looping over the last index too and counting an extra jump.
- In Candy, overwriting the first pass's counts in the second pass instead of taking the
max.
Maximum Subarray
Return the largest sum of any non-empty contiguous run of numbers in nums.
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] → 6 (4, -1, 2, 1)
nums = [5, 4, -1, 7, 8] → 23 (the whole list)
nums = [-3, -1, -2] → -1 (you must pick at least one number)Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
Jump Game
You stand on index 0 of nums. From index i you may jump forward up to nums[i] places. Return true if you can reach the last index.
nums = [2, 3, 1, 1, 4] → true (0 → 1 → 4)
nums = [3, 2, 1, 0, 4] → false (every route lands on the 0 at index 3)
nums = [0] → true (you start at the end)Constraints
1 <= nums.length <= 10^40 <= nums[i] <= 10^5
- greedy algorithm
- Make the locally best choice at each step and never revisit it.
- exchange argument
- Proof that swapping the greedy choice into an optimal answer does not make it worse.
- Kadane's algorithm
- Max subarray in O(n):
cur = max(x, cur + x), track the bestcur. - reach
- In jump game, the farthest index reachable so far. If i ever exceeds it, the end is unreachable.
- counterexample
- A small input where the greedy rule gives a wrong answer, such as coins [1, 3, 4] for amount 6.
- greedy stays ahead
- Proof that after every step, greedy's partial answer is at least as good as any other strategy's by some progress measure.
- BFS levels
- In jump game II, the contiguous range of indexes reachable in exactly k jumps, tracked with level_end and farthest.