Greedy Algorithms
Take the locally best choice at each step - when you can prove it’s safe.
- active this step
- inside the window
- visited / done
- result
From index 0, reach 2
0 + 2 = 2 is the farthest index reachable so far.
VARIABLES
- i
- 0
- farthest
- 2
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A greedy algorithm commits to the best-looking option now and never revisits it. It works when a local choice can be shown to never hurt the final answer.
Why it matters
When it applies, greedy is usually O(n) or O(n log n) and much simpler than DP.
Think of it like this
Paying in rupees with the fewest notes: take the largest note that fits, then repeat. That works for standard currency, not for every coin system.
Use it when
- Interval scheduling - pick whatever finishes earliest
- Reachability, as in Jump Game
- Problems with an exchange-argument proof
Avoid it when
- A counter-example exists - coins [1, 3, 4] for amount 6: greedy uses 3 coins, the best is 2
- You need every solution or exact counts
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Single greedy pass | O(n) | O(1) |
| Sort, then greedy | O(n log n) | O(1) to O(n) |
| DP alternative | often O(n²) | O(n) |
Often confused with: dynamic programming - it weighs every choice; greedy commits to one.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Sorting by end time or by a ratio is a common first step
- If you can’t prove it, test a small counter-example before committing
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Assuming greedy works without a proof or a counter-example check
- Sorting by the wrong key - start time instead of end time for scheduling
- Stopping early when a later element could extend the reach
Edge cases to test
- A single element - already at the end
- A zero that blocks progress, like [3, 2, 1, 0, 4]
- All zeros after the first element
Knowledge check
Quick check to lock in the intuition.
Coins [1, 3, 4], amount 6. Greedy takes 4 first. What is the best possible?
Practice
Apply what you just watched on real interview problems.