Greedy algorithms
Recognise problems with the greedy-choice property and justify a greedy solution.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
A greedy algorithm makes the locally best choice at each step and never revisits it. It works only when the problem has the greedy-choice property, which you justify with an exchange argument. When it applies it is usually simple and fast, often a sort followed by one pass.
Explained simply
A greedy algorithm is like a hungry person at a buffet who always grabs the best-looking dish right now and never puts anything back. It makes the choice that looks best at this moment and moves on. It never goes back to change an earlier choice.
Sometimes that works perfectly. If you want to attend as many meetings as possible, always pick the meeting that ends first. It leaves you the most free time for the rest. Sometimes it fails badly, like paying 6 with coins 1, 3 and 4: taking the biggest coin first gives 4 + 1 + 1 (three coins), but 3 + 3 needs only two.
So the hard part of greedy is not the code. The code is usually a sort plus one loop. The hard part is knowing whether the greedy choice is safe. For that, you either prove it or try hard to break it with small examples.
When greedy works, it is very fast, usually O(n log n) because of the sort. When it does not, the usual fix is dynamic programming, which tries all choices but remembers results so it does not repeat work.
Press Play on a diagram to walk through it one step at a time.
- Step 1Sort by end time
Earliest finishing first.
- Step 2Take first
It leaves the most room.
- Step 3Skip overlaps
Start before last chosen end.
- Step 4Take next compatible
Repeat to the end.
- Most non-overlapping intervals
- Sort by end time
- Merge intervals
- Sort by start time
- Meeting rooms needed
- Sort by start, heap of end times
- Fractional knapsack
- Sort by value per weight, descending
- Minimise maximum lateness
- Sort by deadline
- 1Total check
Gas 15, cost 15: a start exists.
- 2i = 0, 1, 2
Tank goes to -2 each time; restart after.
- 3Start = 3
Tank 4 - 1 = 3.
- 4i = 4
Tank 3 + 5 - 2 = 6.
- 5Answer
Start at station 3.
In depth
The exchange argument, step by step
To prove a greedy choice is safe, take any optimal solution and show you can swap the greedy choice into it without making it worse. For interval scheduling: let g be the meeting that ends first overall. Take any best schedule S and look at its first meeting f. Since g ends no later than f, replacing f with g cannot overlap anything else in S. The new schedule has the same number of meetings, so it is also optimal and it starts with g.
Now repeat the argument on the meetings that start after g ends. By induction, the whole greedy schedule is optimal. Most greedy proofs follow this exact pattern: same size, still valid, contains the greedy choice.
- 1Take any optimum S
It may disagree with greedy.
- 2Find the first difference
S picks f where greedy picks g.
- 3Swap f for g
Show the result is still valid.
- 4Compare cost
It is no worse than S.
- 5Repeat
Induction covers every later choice.
The interval family
Intervals are the most common greedy topic, and the right sort key changes with the question. To keep the most non-overlapping intervals, sort by end time. The minimum number to remove so the rest do not overlap is n minus that count. To merge overlapping intervals, sort by start time and extend the last merged interval. To find the minimum number of meeting rooms, sort by start time and keep a min-heap of end times: if the earliest end is at or before the new start, reuse that room (pop), then push the new end. The heap size at the end is the answer, in O(n log n).
Always ask whether touching intervals like [1, 2] and [2, 3] count as overlapping. Problems differ, and the answer changes whether you compare with < or <=.
- Most non-overlapping: sort by end
- Merge: sort by start
- Rooms needed: sort by start, heap of ends
- Check the touching-endpoints rule
Jump game and gas station
Jump game asks whether you can reach the last index when nums[i] is the longest jump from i. Greedy keeps reach, the furthest index reachable so far. If the loop ever passes reach, you are stuck. For the fewest jumps, treat it like BFS in levels: track the end of the current level and the furthest point the next level can reach. When i reaches the current end, you must jump once more. Both run in O(n).
Gas station: a car drives a circle of stations. If the total gas is less than the total cost, no start works. Otherwise at least one start works, and you find one in a single pass: keep a running tank, and whenever it drops below zero at station i, no station from the current start up to i can be the start, so restart at i + 1 with an empty tank.
Where greedy breaks
Greedy fails when an early cheap choice blocks a better combination later. Coin change with coins 1, 3, 4 is the classic case. With normal coins like 1, 5, 10, 25, greedy happens to be correct, but that is a property of those coins, not of the method.
Knapsack shows the difference sharply. If you may take fractions of items (fractional knapsack), sorting by value per kilogram and filling up is optimal. If items are all-or-nothing (0/1 knapsack), the same rule fails: capacity 50, items (10 kg, 60), (20 kg, 100), (30 kg, 120). Best ratio first takes the first two for 160, but the last two give 220.
To hunt for counterexamples, write a brute force for tiny inputs and compare it with your greedy on thousands of random cases.
- Interval scheduling by end time
- Fractional knapsack by value per weight
- Huffman coding
- Dijkstra and MST
- Coin change with arbitrary coins
- 0/1 knapsack
- Longest path in a graph
- Travelling salesperson
Greedy with a heap
Many greedy algorithms repeatedly need "the best item right now" from a changing set, which is a job for a heap. Huffman coding, used inside compression formats such as DEFLATE, repeatedly merges the two lowest-frequency symbols into one node; each merge costs O(log n) with heapq, so building the code is O(n log n). The same pattern solves "minimum cost to connect sticks": always join the two shortest sticks.
Scheduling problems often combine a sort with a heap: sort tasks by deadline, keep the chosen tasks in a heap, and when the schedule becomes impossible, drop the worst task so far. Each step makes a locally best choice, and an exchange argument justifies it.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Schedule intervals by earliest end time~40m
- 2Merge overlapping intervals~40m
- 3Prove greedy with an exchange argument~40m
- 4Find counterexamples where greedy fails~40m
- 5Solve jump game and gas station~40m
Key points
- Typical cost: O(n log n) for the sort plus O(n) for the scan.
- Exchange argument: swapping any optimal choice for the greedy one never makes it worse.
- Coin change with denominations 1, 3, 4 and amount 6 breaks greedy (4+1+1 vs 3+3).
- If a small counterexample exists, switch to dynamic programming.
Key terms
Tap a card to flip it. 0/3 known
Examples
def merge_intervals(intervals): # O(n log n)
out = []
for start, end in sorted(intervals):
if out and start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
def can_jump(nums): # O(n)
reach = 0
for i, x in enumerate(nums):
if i > reach: return False
reach = max(reach, i + x)
return TrueFewest intervals to remove
Intervals [1,2], [2,3], [3,4], [1,3]. Touching ends do not overlap here. Step 1: sort by end: [1,2], [2,3], [1,3], [3,4]. Step 2: keep [1,2], end = 2. Step 3: [2,3] starts at 2, which is not before 2, so keep it, end = 3. Step 4: [1,3] starts before 3, so remove it. Step 5: [3,4] is fine, keep it. We kept 3, so we remove 4 - 3 = 1.
def erase_overlaps(intervals): # O(n log n)
kept, end = 0, float("-inf")
for s, e in sorted(intervals, key=lambda x: x[1]):
if s >= end: # no overlap with the last kept one
kept += 1
end = e
return len(intervals) - kept
print(erase_overlaps([[1, 2], [2, 3], [3, 4], [1, 3]])) # 1
print(erase_overlaps([[1, 2], [1, 2], [1, 2]])) # 2Gas station in one pass
This is the trace from the diagram turned into code. The variable total checks whether any answer exists. The variable tank tracks fuel since the current candidate start. When tank goes negative at i, every start from the candidate to i would also fail at i (each of them arrives with no more fuel), so the next candidate is i + 1. Time O(n), space O(1).
def can_complete_circuit(gas, cost):
total = tank = start = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
tank += diff
if tank < 0: # cannot reach i + 1 from start
start, tank = i + 1, 0
return start if total >= 0 else -1
print(can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])) # 3
print(can_complete_circuit([2, 3, 4], [3, 4, 3])) # -1Quick reference
- Greedy cost is usually O(n log n) for the sort plus O(n) for one pass
- Max non-overlapping intervals: sort by end; removals = n - kept
- Merge intervals: sort by start and extend the last one
- Meeting rooms: sort by start, min-heap of end times, answer = heap size
- Gas station: total gas < total cost means -1; else restart after each negative tank
- Coins 1, 3, 4 and amount 6 break greedy: 4+1+1 vs 3+3
- Fractional knapsack is greedy; 0/1 knapsack needs DP
- Test a greedy idea against brute force on many small random inputs
Common mistakes
- Trusting greedy without a proof or counterexample search.
- Sorting by start time when the argument needs end time.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Each child i needs a cookie of size at least greed[i]. Each cookie goes to at most one child. Return the most children you can satisfy. Example: greed [1, 2, 3], sizes [1, 1] gives 1.
- Exercise 2medium
nums[i] is the longest jump from index i. You can always reach the end. Return the fewest jumps needed. Example: [2, 3, 1, 1, 4] gives 2.
- Exercise 3hard
Children stand in a line with ratings. Each child gets at least one candy, and a child with a higher rating than a neighbour must get more than that neighbour. Return the minimum total. Example: [1, 0, 2] gives 5.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know if a problem can be solved greedily?
- Look for a choice you can prove is always safe, usually with an exchange argument. If you cannot prove it, try to break it with tiny inputs and a brute-force checker; if it breaks, switch to DP.
- What is the difference between greedy and dynamic programming?
- Greedy commits to one choice per step and never reconsiders. DP considers every choice for each subproblem and keeps the best, which is slower but works when the locally best choice can be wrong.
- Is Dijkstra's algorithm greedy?
- Yes. It always finalises the closest unfinished vertex, and the non-negative weights are exactly what makes that greedy choice safe. Kruskal and Prim are greedy too.
- Why is greedy correct for coin change with normal coins?
- Systems like 1, 5, 10, 25 are designed so the largest coin is always part of some best answer. This is a property of those specific coins, called a canonical coin system, and fails for sets like 1, 3, 4.