When does a greedy algorithm work, and when do you need dynamic programming instead?
AlgorithmsMid-level
In shortGreedy works when a locally best choice can never block a better overall result, which you show with an exchange argument. When an early choice can rule out a better combination, as with coins [1, 3, 4], you need DP.
Model answer
A greedy algorithm makes the best-looking choice at each step and never revisits it. It’s correct when two things hold:
- Greedy-choice property: some optimal solution starts with the greedy choice.
- Optimal substructure: after that choice, the rest is the same kind of problem, solved by the same rule.
You justify it with an exchange argument: take any optimal solution, swap its first choice for the greedy one, and show it doesn’t get worse. Interval scheduling (keep the meeting that ends earliest) is the classic example.
Greedy fails when an early choice can block a better combination. Coins [1, 3, 4] and amount 6: biggest-first takes 4 + 1 + 1 (3 coins), but 3 + 3 uses 2. 0/1 knapsack fails the same way. Those problems need dynamic programming, which considers every choice and reuses the answers to smaller subproblems.
In practice: state the greedy rule, try two or three tiny counterexamples, and only commit to greedy if you can explain why swapping never helps.
What they're looking for
The greedy-choice property and optimal substructure in plain words, one proof technique (exchange argument or greedy stays ahead), and a concrete counterexample where greedy fails.
Common mistakes
- Saying greedy is "faster DP" without explaining when it's correct.
- Not being able to give a counterexample.
- Claiming coin change is always greedy.
More algorithms questions
- How do you work out and explain the time and space complexity of your solution?Junior
- What's the difference between a stack and a queue, and when would you use each?Junior
- How do you find the first occurrence of a value in a sorted array that has duplicates?Mid-level
- When would you use BFS instead of DFS, and vice versa?Mid-level