Loading...
Master memoization, tabulation, and advanced DP patterns
Section 1 of 5
DP breaks a complex problem into overlapping subproblems with optimal substructure, solving each subproblem once and reusing results.
Dynamic Programming = Recursion + Memoization. Use it when subproblems repeat (overlap) and the global optimum can be built from optimal sub-solutions (optimal substructure).
Naive recursion is exponential. DP reduces it to linear time.
1function fib(n):2 if n <= 1: return n3 if memo[n] exists: return memo[n]4 memo[n] = fib(n-1) + fib(n-2)5 return memo[n]Visualize how a 2D DP fills cell-by-cell with the LCS of “ABCBDAB” and “BDCABA”.
| B | D | C | A | B | A | ||
|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
| A | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| B | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| C | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| B | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| D | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| B | 0 | 0 | 0 | 0 | 0 | 0 | 0 |