Algorithms Playbook
PatternTime O(n) or O(n log n) · Space O(1)8 min read

Greedy: take the best local choice and never look back

A greedy algorithm makes the best-looking choice at every step and is never undone. When it's correct, how to argue it, and how to tell it apart from DP.

In short

Greedy picks the locally best option at each step and never reconsiders. It's fast (often one pass, or a sort plus one pass) but only correct when a local choice is provably safe. If a small counterexample breaks it, use DP.

The idea: one number is enough

Jump game: each cell says how far you can jump from it; can you reach the last cell? You don't need to explore paths. Track one number: the farthest index reachable so far. If you ever stand beyond it, you're stuck; otherwise update it with i + nums[i].

Jump game: one greedy number, the farthest reach
Speed
0213213144reacheach value = max jump from that cell
1def can_jump(nums):
2 reach = 0
3 for i, step in enumerate(nums):
4 if i > reach:
5 return False
6 reach = max(reach, i + step)
7 return True
reach = the farthest index we know we can get to. Right now only index 0.

Variables

reach0
Step 1/7· Steps: 0
Greedy in one line: we never need to remember which path got us there, only how far we can possibly get. Try 3, 2, 1, 0, 4: the zero is a wall that reach can't cross.

Greedy or DP?

Greedy works when…

  • A local best choice is part of some optimal answer
  • You can swap any optimal solution into the greedy one (exchange argument)
  • Typical: interval scheduling, jump game, gas station, assigning cookies

Use DP when…

  • A small counterexample breaks the greedy choice
  • Coins 1, 3, 4 and amount 6: greedy gives 3 coins, optimal is 2
  • You need to compare several options, not just pick one

The classic: max non-overlapping meetings

To fit the most meetings in one room, sort by end time and keep each meeting that starts after the last chosen one ends. Why end time? A meeting that finishes earliest leaves the most room for the rest. Sorting by start time or by duration both have counterexamples.

intervals.sort(key=lambda m: m[1])      # by end time
last_end, count = -inf, 0
for start, end in intervals:
    if start >= last_end:
        count += 1
        last_end = end

Key takeaways

  • 01Greedy = best local choice, never reconsidered.
  • 02Look for a sort or a single running value that makes the choice obvious.
  • 03Always try a tiny counterexample; if it breaks, switch to DP.
  • 04Cost is usually O(n) or O(n log n) because of the sort.

Check your understanding

1 of 3

What does a greedy algorithm do?

Related topics