Dynamic Programming

Difficulty
Importance

The problem

Some recursive problems recompute the same subproblem exponentially many times (naive Fibonacci being the classic case), wasting enormous work — dynamic programming eliminates that waste by remembering (caching) subproblem answers instead of recomputing them.

Why now

Recurrence relations already showed that a naive recursive solution's cost is governed by its recurrence, and that recurrence can be exponential. Dynamic programming is the direct fix: store each subproblem's answer once, in a table or cache, turning an exponential recurrence into a polynomial one by trading memory for time.

Mental model

If you've solved a subproblem before, don't solve it again — write the answer down and look it up next time. That's the entire idea; 'dynamic programming' is just disciplined memoization, either top-down (recursion plus a cache) or bottom-up (filling a table from the smallest subproblems up).

Requires

Helps

Used in

Projects

  • Implement naive recursive Fibonacci, time it at n=35, then add memoization and compare the runtime difference directly
  • Solve the edit-distance problem (minimum operations to transform one string into another) using bottom-up dynamic programming

Examples

  • Naive fib(40) makes over a billion redundant calls; memoized fib(40) makes 40
  • A spell checker's 'did you mean' suggestion is powered by edit-distance dynamic programming

Resources

Mastery checklist