Learn the pattern · ~15 min
Greedy
also called exchange argument, greedy stays ahead, local choice
Make the choice that looks best right now and never undo it, but only after you can show, usually by swapping, that some best answer makes the same choice.
Reach for it when you read
- +One pass where a single running value (farthest reach, last end, running sum) decides everything.
- +Intervals and "the fewest points / most non-overlapping": sort by end, take the earliest end.
- +A local rule you can defend with an exchange argument: swapping a best answer's choice for yours never makes it worse.
- +Constraints like n = 10⁵ that rule out DP over pairs, and no choice ever needs to be undone.
Not this one when
- ×Coin change with arbitrary coins (1, 3, 4 for 6): the biggest coin first fails; DP.
- ×0/1 knapsack: the best value-per-weight item first can fail; DP.
- ×A rule you haven't tried to break on 3–4 small inputs.
Learn Greedy
First, what does "greedy" mean?
A greedy algorithm makes the choice that looks best right now, and never takes it back.
Pay 18 with as few coins of 1, 5 and 10 as you can. Greedy: take the biggest coin that fits, again and again. 10, 5, 1, 1, 1: five coins, the best.
Now pay 6 with coins of 1, 3 and 4. Greedy takes 4, 1, 1: three coins. But 3 + 3 is two.
So a greedy rule needs a reason it loses nothing. This lesson uses the exchange argument: take any best answer, swap its choice for the greedy one, and show it's still a best answer.
How does a greedy rule look?
Jump Game. nums[i] is the longest jump you can make from index i. Starting at index 0, can you reach the last index of [2, 1, 3, 0, 0, 2]?
Don't decide which jumps to make. Keep one number, reach: the farthest index you can get to so far.
At each index you can stand on, update
reach = max(reach, i + nums[i]). If you ever arrive at an index beyondreach, you're stuck.
| i | nums[i] | i + nums[i] | what happens | reach |
|---|---|---|---|---|
| 0 | 2 | 2 | from 0 you get as far as 2 | 2 |
| 1 | 1 | 2 | 1 ≤ 2: we can stand here; no better | 2 |
| 2 | 3 | 5 | 2 ≤ 2: we can stand here; it reaches 5, the last index | 5 |
| 3 | 0 | 3 | 3 ≤ 5: we can stand here; no better | 5 |
| 4 | 0 | 4 | 4 ≤ 5: we can stand here; no better | 5 |
| 5 | 2 | 7 | 5 ≤ 5: we're on the last index | 7 |
We were never stuck, so yes. On [3, 1, 0, 0, 2], reach stops at 3 and index 4 is beyond it: no.
The code for it
bool canJump(const vector<int>& nums) {
int reach = 0; // farthest index we can stand on so far
for (int i = 0; i < (int)nums.size(); i++) {
if (i > reach) return false; // can't even stand here
reach = max(reach, i + nums[i]);
}
return true;
}You don't need to memorise this. It's the table: walk, give up past reach, else stretch it.
Why is one number enough, when there are many ways to jump? Because every index up to reach can be stood on: reach came from some index j you stood on, and from j you may jump any length up to nums[j], not only the longest. So a bigger reach includes every option a smaller one had.
Careful: "always make the longest jump" sounds the same but is wrong. On [2, 3, 1, 0, 4] it goes 0 → 2 → 3 and sits on the 0, while 0 → 1 → 4 works. Keep the farthest reach, not the farthest jump.
Fine, but how does this help us?
The classic problem: Minimum Number of Arrows to Burst Balloons. Each balloon is an interval [start, end]; an arrow at x bursts every balloon with start ≤ x ≤ end. What's the fewest arrows that burst them all?
For [3,7] [1,4] [6,9] [8,12] [11,13], by hand:
| balloon | arrow | how you found it |
|---|---|---|
| [1, 4] | at 4 | 4 is inside both [1, 4] and [3, 7] |
| [3, 7] | at 4 | same arrow |
| [6, 9] | at 9 | 9 is inside both [6, 9] and [8, 12] |
| [8, 12] | at 9 | same arrow |
| [11, 13] | at 13 | it doesn't overlap [6, 9] or anything before |
Could two arrows do it? No: [1,4], [6,9] and [11,13] don't overlap, so no arrow hits two of them. The answer is 3.
The brute force
Try every set of arrow spots and keep the smallest that bursts everything. An arrow can slide right until it sits on some balloon's end, so only the ends are worth trying.
int arrowsBrute(const vector<vector<int>>& p) {
int n = p.size(), best = n;
for (int mask = 0; mask < (1 << n); mask++) { // every set of ends
bool all = true;
for (auto& b : p) {
bool hit = false;
for (int j = 0; j < n; j++)
if (mask >> j & 1 && b[0] <= p[j][1] && p[j][1] <= b[1]) hit = true;
all = all && hit;
}
if (all) best = min(best, __builtin_popcount(mask));
}
return best;
}That's 2ⁿ sets, each checked in O(n²). At n = 22 it took 3 seconds (measured), and every extra balloon doubles that; LeetCode allows n = 10⁵. Time limit exceeded.
The one thought that fixes it
Look at the balloon that ends first, [1, 4]. Every answer must burst it, so some arrow sits at an x ≤ 4.
Slide that arrow right, to exactly 4. Does it miss anything? Take any balloon it hit at x:
- its start is ≤ x, so its start is ≤ 4;
- its end is ≥ 4, because no balloon ends before
[1, 4]does.
So the balloon still contains 4: the arrow at 4 hits everything the arrow at x hit, and maybe more. That's the exchange argument: whatever a best answer did for [1, 4], swapping in "shoot at 4" keeps it just as good.
Then the same question is left for the balloons 4 didn't burst. So: sort by end, shoot at the first end not yet burst, skip what it bursts, repeat.
sort(p.begin(), p.end(), [](auto& a, auto& b) { return a[1] < b[1]; }); // by end
int arrows = 0;
long long shot = -1e18; // where the last arrow went
for (auto& b : p) {
if (b[0] <= shot) continue; // shot <= b's end (sorted), so it's burst
shot = b[1]; arrows++; // shoot at the smallest end left
}Dry run
Sorted by end: [1,4] [3,7] [6,9] [8,12] [11,13].
| balloon | last shot | what happens | arrows |
|---|---|---|---|
| [1, 4] | none | not burst: shoot at its end, 4 | 1 |
| [3, 7] | 4 | 3 ≤ 4 (and 4 ≤ 7): burst | 1 |
| [6, 9] | 4 | 6 > 4: shoot at 9 | 2 |
| [8, 12] | 9 | 8 ≤ 9: burst | 2 |
| [11, 13] | 9 | 11 > 9: shoot at 13 | 3 |
3 arrows, the same answer as the brute force.
A tempting wrong rule
"Sort by start, and shoot at the end of each balloon still standing." On our five balloons it also gives 3. Now try [1,10] [2,3] [4,5]:
- the start rule shoots at 10 (only
[1,10]bursts), then at 3, then at 5: 3 arrows; - the end rule shoots at 3 (bursting
[2,3]and[1,10]), then at 5: 2 arrows.
The long balloon that starts first fooled it: the exchange works only for the balloon that ends first.
Why it's O(n log n)
The sort is O(n log n). After it, each balloon gets one comparison: O(n). For n = 10⁵, about 1.7 × 10⁶ steps. Space: O(1) besides the sort.
From every set of spots to one pass, because one safe choice at a time is enough.
Fewest jumps? Count the blocks
Jump Game II asks for the fewest jumps. Think in blocks: what one jump reaches, then two. When i hits the end of a block, one more jump is spent:
reach = max(reach, i + nums[i]);
if (i == end) { jumps++; end = reach; } // this block is used up: one more jumpRun i only up to n − 2: on the last index, no jump is needed. On [2, 1, 3, 0, 0, 2] that's 2 jumps (0 → 2 → 5).
Reach on letters: Partition Labels
Cut a string into as many pieces as possible, each letter in only one piece. reach is now the last position of any letter seen so far:
reach = max(reach, last[s[i] - 'a']); // this letter must stay in the piece
if (i == reach) { out.push_back(i - start + 1); start = i + 1; }"ababcbacadefegdehijhklij" gives pieces of length 9, 7, 8.
Restart the running sum: Gas Station
If the tank goes negative at i, no start from the last restart up to i works:
tank += g[i] - c[i];
if (tank < 0) { start = i + 1; tank = 0; } // no start up to i works: restart after itIf total gas < total cost, no start works: return −1. With gas [1, 2, 3, 4, 5] and cost [3, 4, 5, 1, 2], start at index 3.
Remember this
- A greedy rule needs a reason. Prove it by exchange: the greedy choice can replace whatever a best answer chose.
- Try to break every rule on 3–4 items first, like coins 1, 3, 4 or
[1,10] [2,3] [4,5]. - Fewest points or most non-overlapping intervals: sort by end.
- Whenever a problem asks for "the best result, and one safe choice at a time builds it", it's greedy.
Practise it on Jump Game, then Jump Game II (reach in blocks), Minimum Number of Arrows to Burst Balloons (sort by end), Partition Labels (reach on letters), Gas Station (restart the sum) and Task Scheduler (reason about the most frequent).
Below, watch Jump Game run line by line.
Watch it work, line by line
Jump Game ↗, nums = [3, 2, 1, 0, 4] → false (every path lands on the 0 at index 3). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is there a choice I can make now, without looking ahead, and would swapping it into any best answer never make that answer worse?
Reach for it when
- +sort by a key then make one pass
- +an obvious 'always take the cheapest/earliest-ending/furthest-reaching'
- +optimal substructure with no need to revisit choices
- +n up to 1e5-1e6 (usually O(n log n) sort)
It fails when
- ×Choices interact later (knapsack, weighted scheduling)use Dynamic programming
- ×A small counterexample breaks the rule (coin change, non-canonical coins)use DP
- ×You need to count ways or explore alternativesuse DP or backtracking
- ×You think passing the samples means it's correctuse Try to break it on small adversarial cases first
Looks like it, isn't (and the other way round)
- Jump Game II looks like 1D / Fibonacci-style, needs this pattern
O(n2) DP works but the greedy BFS over reach windows is O(n).
- Task Scheduler looks like Top-K Elements, needs this pattern
A heap simulation works, but a counting formula on the max frequency gives O(n).
- Valid Parenthesis String looks like Stack for Matching & Expression Parsing, needs this pattern
'*' makes stacks branch; track a range [lo, hi] of open counts.
- Minimum Number of Taps to Open to Water a Garden looks like Interval DP, needs this pattern
Convert each tap to its reach interval; the jump-game-ii farthest-reach greedy covers [0, n] in O(n).
- Russian Doll Envelopes looks like Greedy, needs Longest Increasing Subsequence
Greedy by width fails; sort (w asc, h desc) and run LIS on heights.
- Binary Tree Cameras looks like Greedy, needs DP on Trees
Top-down greedy (cameras on the leaves) fails. A three-state tree DP works, and so does the bottom-up greedy (a camera at the parent of the deepest uncovered node), which the DP proves.
- Delete and Earn looks like Greedy, needs 1D / Fibonacci-style
Taking x deletes x-1 and x+1: after bucketing values it is house robber.
- Coin Change looks like Greedy, needs Unbounded Knapsack
Largest-coin-first fails for arbitrary denominations.
- Remove K Digits looks like Greedy, needs Monotonic Stack
The greedy 'drop a digit larger than the next' is implemented by a monotonic stack.
- Minimum Cost to Move Chips to The Same Position looks like Greedy, needs Invariants & Parity Arguments
Moves by 2 are free, so only parity matters: the answer is min(#odd, #even).
- Largest Number looks like Greedy, needs Exchange-Argument Sorting (custom comparator)
Sorting by value fails ('3' vs '30'). The editorial uses a custom comparator a+b vs b+a.
- Minimum XOR Sum of Two Arrays looks like Greedy, needs Bitmask DP
Assignment with n <= 14. Greedy pairing fails. dp[mask] over the matched elements of nums2 (Hungarian / min-cost-flow also works).
- Minimum Total Distance Traveled looks like Greedy, needs LCS / Two-Sequence
Nearest-factory greedy fails on capacities. After sorting, an optimal matching is non-crossing, which gives a two-sequence DP (editorial memoisation).
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1How do you know a greedy choice is correct?Reveal
Show that some best answer agrees with it: swap the greedy choice into any optimal answer and check that it never gets worse.
2In Jump Game, when do you return false?Reveal
When
i > reach: you've arrived at an index that no earlier index can jump to.3Coins 1, 3, 4 and amount 6: what does greedy give, and what's best?Reveal
Greedy gives 4 + 1 + 1, three coins. The best is 3 + 3, two coins. So coin change needs DP.
Practice ladder
- 1Best Time to Buy and Sell Stock IItake every upward stepMedium
- 2Jump Gamethe hookMedium
- 3Jump Game IIreach in levelsMedium
- 4Minimum Number of Arrows to Burst Balloonssort by endMedium
- 5Partition Labelsreach on lettersMedium
- 6Gas Stationrestart the running sumMedium
- 7Task Schedulerreason about the most frequentMedium
- 8Candytwo passesHard
Finished Greedy? Mark it done and Lessgo moves you to the next step.