Skip to content
Visual explainer 3h 30m to learn 5 steps

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.

Topic 39 of 54

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.

FlowInterval scheduling: maximum non-overlapping meetings
  1. Step 1
    Sort by end time

    Earliest finishing first.

  2. Step 2
    Take first

    It leaves the most room.

  3. Step 3
    Skip overlaps

    Start before last chosen end.

  4. Step 4
    Take next compatible

    Repeat to the end.

MapPick the sort key for the question
Greedy on a list
  • 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
FlowGas station: gas [1,2,3,4,5], cost [3,4,5,1,2]
  1. 1
    Total check

    Gas 15, cost 15: a start exists.

  2. 2
    i = 0, 1, 2

    Tank goes to -2 each time; restart after.

  3. 3
    Start = 3

    Tank 4 - 1 = 3.

  4. 4
    i = 4

    Tank 3 + 5 - 2 = 6.

  5. 5
    Answer

    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.

FlowShape of an exchange argument
  1. 1
    Take any optimum S

    It may disagree with greedy.

  2. 2
    Find the first difference

    S picks f where greedy picks g.

  3. 3
    Swap f for g

    Show the result is still valid.

  4. 4
    Compare cost

    It is no worse than S.

  5. 5
    Repeat

    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.

CompareGreedy works or fails
Greedy is optimal
  • Interval scheduling by end time
  • Fractional knapsack by value per weight
  • Huffman coding
  • Dijkstra and MST
Greedy can fail
  • 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.

  1. 1
    Schedule intervals by earliest end time~40m
  2. 2
    Merge overlapping intervals~40m
  3. 3
    Prove greedy with an exchange argument~40m
  4. 4
    Find counterexamples where greedy fails~40m
  5. 5
    Solve 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

python
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 True

Fewest 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.

python
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]]))          # 2

Gas 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).

python
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]))              # -1

Quick 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.

Question 1

1To keep the maximum number of non-overlapping intervals, what should you sort by?

Question 2

2Intervals [1,10], [2,3], [4,5]. A greedy sorted by start time takes [1,10] first. How many does it keep, and what is optimal?

Question 3

3Capacity 50, items (10 kg, 60), (20 kg, 100), (30 kg, 120), whole items only. What does best-ratio-first greedy get?

Question 4

4In gas station, the tank becomes negative at station 5 when starting from station 2. What can you conclude?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. 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.

  2. 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.

  3. 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.

Go deeper

ShareXLinkedInWhatsApp