← Learning Hub
Advanced

Greedy Algorithms and Backtracking

Greedy algorithms make the best-looking choice at each step and never look back - fast, but only correct for certain problems. Backtracking explores choices one by one and undoes them when they fail, which is how you generate combinations or solve puzzles.

Greedy: take the best choice now

A greedy algorithm picks the best-looking option at each step and never looks back. It is fast, but only correct for some problems - you must be able to argue why.

Example
You can edit this code.

Greedy works for Indian coins (1, 2, 5, 10...) - always take the biggest coin - but fails for coins like 1, 3, 4: for 6 it gives 4+1+1 (three coins) while 3+3 needs only two. That's when you need DP.

Backtracking: try, and undo if it fails

Backtracking builds a solution step by step and goes back when a choice leads nowhere. It explores all possibilities, so it's used for puzzles, permutations and combinations.

Example
You can edit this code.
Example
You can edit this code.
Key points
  • Greedy: pick the locally best choice; prove it works first.
  • Backtracking: choose, explore, un-choose.
  • Backtracking explores many possibilities, so prune early.

📝 Test yourself

1. What does a greedy algorithm do?
2. What is the key step of backtracking?
3. For coins 1, 3, 4 and amount 6, greedy gives 3 coins. What is the best?