Greedy
Reach for it when the problem says
- Jump games
- scheduling
- "maximum number of…"
- Solved
- 0/31Solved
- Problems
- 31Problems
- Variants
- 7Variants
Problems
7 variantsRunning sum and reset
0 of 5 solved- Maximum SubarraySprintDeep diveMediumDecode Maximum Subarray
- Gas StationSprintDeep diveMediumDecode Gas Station
- Best Time to Buy and Sell Stock IISprintDeep diveMediumDecode Best Time to Buy and Sell Stock II
- Maximum Sum Circular SubarraySprintDeep diveMediumDecode Maximum Sum Circular Subarray
- Text JustificationSprintDeep diveHardDecode Text Justification
Reach and coverage
0 of 3 solved- Jump GameSprintDeep diveMediumDecode Jump Game
- Jump Game IISprintDeep diveMediumDecode Jump Game II
- Partition LabelsDeep diveMediumDecode Partition Labels
Sort then take
0 of 7 solved- Assign CookiesUp nextDeep diveEasyDecode Assign Cookies
- Maximum Units on a TruckDeep diveEasyDecode Maximum Units on a Truck
- Maximum Ice Cream BarsDeep diveMediumDecode Maximum Ice Cream Bars
- Reduce Array Size to The HalfDeep diveMediumDecode Reduce Array Size to The Half
- Hand of StraightsDeep diveMediumDecode Hand of Straights
- Bag of TokensDeep diveMediumDecode Bag of Tokens
- Minimum Deletions to Make Character Frequencies UniqueMediumDecode Minimum Deletions to Make Character Frequencies Unique
Custom sort order
0 of 3 solvedCounters and balance
0 of 3 solvedLocal rule scan
0 of 6 solved- Can Place FlowersEssentialsDeep diveEasyDecode Can Place Flowers
- Kids With the Greatest Number of CandiesEssentialsDeep diveEasyDecode Kids With the Greatest Number of Candies
- Increasing Triplet SubsequenceEssentialsDeep diveMediumDecode Increasing Triplet Subsequence
- Wiggle SubsequenceMediumDecode Wiggle Subsequence
- Merge Triplets to Form Target TripletDeep diveMediumDecode Merge Triplets to Form Target Triplet
- CandySprintDeep diveHardDecode Candy
Most significant first
0 of 4 solvedPattern guide
A greedy algorithm makes the choice that looks best right now, commits to it, and never revisits it. When it is correct it is usually the shortest and fastest solution you can write: one sort, one pass, a couple of variables. That is why interviewers love greedy problems, and also why they love asking "how do you know that is right?"
This page is about answering that question. You will learn the seven shapes greedy problems come in, how to recognise each one from the prompt, and the one argument (the exchange argument) that turns a hunch into a proof.
What it is
Greedy works when a local choice can never hurt the final answer. You prove that with an exchange argument: take any optimal answer that disagrees with your greedy choice, swap the greedy choice in, and show the answer is no worse. If that swap always works, greedy is safe. If you can find an input where the swap makes things worse, greedy is wrong and you probably need dynamic programming.
Here is the cleanest example, Jump Game. From index i you may jump up to nums[i] places. Can you reach the end? You never decide which jump to take. You only track reach, the furthest index any visited cell can reach, because the reachable cells always form a prefix.
From index 0 you can reach up to index 0 + 2 = 2. Everything in 0..2 is reachable.
There was no choice to get wrong, because one number summarised every possible path. Most greedy solutions look like this: find the one quantity that summarises everything, then update it in a single pass.
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "maximum number of", "minimum number of" | Count-based optimisation. Often take the cheapest or most valuable item first. |
| "in any order", "you may rearrange" | You are free to sort. Sort by the key that makes the swap argument work. |
"at most one", "up to k places" | A reach or capacity. Track the furthest point or the remaining room. |
| "as many pieces as possible" | Cut as early as you legally can. |
| "is it possible", "return true if" | Often a single running quantity decides it (reach, tank, balance). |
| "as many times as you like" | No limit on actions, so you can grab every small gain. |
| "largest number", "largest value" with digits | Most significant digit first. |
Constraint clues
| Constraint | What it suggests |
|---|---|
n <= 10^5 or more | O(n) or O(n log n). A sort plus a pass is the usual shape. |
Values or capacities up to 10^8 or 10^9 | A DP indexed by value or capacity is too wide. Greedy or sorting it is. |
n <= 20 with flips or choices | Brute force over 2^n might pass, but check for a greedy rule on bit weight first. |
| "O(1) extra space" | Two or three running variables, not a table. |
Input and output shape clues
- A list of items, each with a cost and a value, and a limit on how many you take: sort by value and take the best.
- A sequence you scan once, and the answer is a yes/no or a single number: a running quantity with a reset rule.
- Pairs of choices per item (city A or B, face up or face down): sort by the difference between the two options.
- A number or grid of bits to maximise: handle the most significant position first.
Looks like greedy but isn't
- Coin change with arbitrary coins. "Take the biggest coin" fails for coins
[1, 3, 4]and amount 6 (greedy 4+1+1, best 3+3). Use dynamic programming. - 0/1 knapsack. "Best value per weight first" fails when items cannot be split. Maximum Units on a Truck is greedy only because every box takes the same single slot.
- Interval scheduling with weights. Earliest end time is optimal when every meeting counts the same. Once meetings have profits (Maximum Profit in Job Scheduling) you need DP.
- Longest increasing subsequence. Increasing Triplet is greedy because the length is fixed at three. General LIS needs DP or patience sorting.
Match each problem to the right tool.
The sub-patterns
Running sum and reset
Use it when you scan a sequence, keep a running total, and the rule is "once the total turns bad, nothing before this point can help". Kadane's algorithm is the template: a negative prefix only drags down what comes next, so drop it.
The gains gas[i] - cost[i] for gas [1,2,3,4,5] and cost [3,4,5,1,2]. The tank is negative at once, so start moves to 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Problems: Maximum Subarray, Gas Station, Best Time to Buy and Sell Stock II, Maximum Sum Circular Subarray.
Reach and coverage
Use it when each position extends how far you can get, and you only care about the frontier. Jump Game tracks one reach. Jump Game II tracks the current level's end and the next level's furthest point, which is BFS without a queue. Partition Labels extends a piece to the furthest last occurrence of any letter inside it.
The last a is at index 3, so this piece cannot close before 3.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Problems: Jump Game, Jump Game II, Partition Labels.
Sort then take
Use it when every item counts the same toward the answer and you must pick some of them under a limit. Sort so the best item is first, then take items until the limit stops you. The swap argument is always the same: if a best answer used a worse item while a better one sat unused, swapping them is no worse.
Cookies sorted: [1, 1, 2, 3]. Children sorted by greed: [1, 2, 3].
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) time for the sort, O(n) space. Problems: Assign Cookies, Maximum Units on a Truck, Hand of Straights, Bag of Tokens, Reduce Array Size to The Half.
Custom sort order
Use it when the answer is an ordering or a split, and the right order is not "by value". Find the key by asking what two neighbours compare on. In Two City Scheduling the key is a - b, the saving from city A. In Largest Number the rule is a + b > b + a as strings. In Queue Reconstruction it is tallest first, then smallest k.
Costs to A and B. Exactly two people must go to each city.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) for the sort (Queue Reconstruction adds O(n²) for list inserts). Problems: Two City Scheduling, Largest Number, Queue Reconstruction by Height.
What does this print?
from functools import cmp_to_key
parts = ["3", "30", "34"]
parts.sort(key=cmp_to_key(lambda a, b: -1 if a + b > b + a else 1))
print("".join(parts))Counters and balance
Use it when the state that matters is a count (open brackets, bills in the till), and each character or event moves it up or down. Sometimes the count is a range: in Valid Parenthesis String a * widens the range of possible open counts to low..high.
An open bracket: one open, whatever the stars do.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Problems: Valid Parenthesis String, Minimum Add to Make Parentheses Valid, Lemonade Change.
Local rule scan
Use it when a simple rule at each position, applied left to right (sometimes again right to left), gives the global answer. Plant a flower in the first legal plot. Keep the smallest first and second numbers for an increasing triplet. Count peaks and valleys for a wiggle. Candy uses two passes, one per neighbour rule.
Everyone starts with one candy.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) or O(n) space. Problems: Can Place Flowers, Increasing Triplet Subsequence, Wiggle Subsequence, Candy, Merge Triplets to Form Target Triplet.
Most significant first
Use it when the answer is a number built from digits or bits. The leftmost position outweighs everything after it (in binary, 1000 beats 0111), so settle the most significant position first, as well as you can, and only then look at the rest. Broken Calculator is the same idea run backward: from the target, halving is the big move, so take it whenever the number is even.
Each row is a binary number. The first column is worth 8, more than the other three columns together.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(digits) or O(log n) for numbers, O(m · n) for a grid. Problems: Maximum Swap, Monotone Increasing Digits, Score After Flipping Matrix, Broken Calculator.
A decision checklist
Go through these questions in order. The first yes usually names the sub-pattern.
Match the clue to the greedy sub-pattern.
Put the steps of solving a greedy problem in order.
- Tap the steps below in the right order.
Traps
- Initialising from 0 instead of the first element. Kadane on
[-3, -1, -2]must return-1, not0. Startbestandcurrentatnums[0]. - Stopping one step too late. Jump Game II loops to
len(nums) - 2; looping to the end can count an extra jump from the last index. - Overwriting instead of taking the max. Candy's second pass must keep
max(given[i], given[i + 1] + 1), or it breaks the first pass's rule. - Strict versus non-strict comparisons. Increasing Triplet uses
<=so equal values never count. Gas Station resets only when the tank goes strictly below 0. - Forgetting the all-zero or empty case. Largest Number on
[0, 0]must return"0". Bag of Tokens on an empty bag returns 0. - Sorting by the obvious key. Largest Number fails with numeric order and with plain string order. Two City Scheduling fails if you sort by
aalone. - Mutating the caller's input. Can Place Flowers marks plots as it plants. Work on a copy.
Edge cases to always test: one element, all equal, already optimal, strictly increasing and strictly decreasing input, and the smallest input where greedy has a real choice.
best = 0 and current = 0. Which input breaks it?How to talk it through
- Greedy algorithm
- Builds the answer by making the locally best choice at each step and never undoing it.
- Exchange argument
- A proof that swapping the greedy choice into any optimal answer does not make it worse.
- Kadane's algorithm
- Maximum subarray in one pass: extend the current run or restart, whichever is larger.
- Reach
- The furthest index reachable so far. Because reachable cells form a prefix, one number summarises them all.
- Custom comparator
- A sort rule other than plain value order, such as
a + b > b + afor Largest Number. - Most significant first
- When building a number, settle the leftmost digit or bit first, since it outweighs everything after it.