Dynamic Programming (DP) is a powerful algorithmic paradigm used to solve complex optimization problems by breaking them down into simpler, overlapping subproblems. Rather than recomputing solutions to identical subproblems repeatedly, DP computes each subproblem solution exactly once and stores the result in memory (caching).
A problem can be solved with Dynamic Programming if and only if it exhibits both of the following mathematical properties:
$$\text{Fib}(5) = \text{Fib}(4) + \text{Fib}(3)$$ $$\text{Fib}(4) = \text{Fib}(3) + \text{Fib}(2)$$ Notice that $\text{Fib}(3)$ is computed twice, $\text{Fib}(2)$ three times, leading to explosive $O(2^n)$ exponential duplication!
| Feature | Top-Down (Memoization) | Bottom-Up (Tabulation) |
|---|---|---|
| Flow of Execution | Root to Leaves (Target down to Base Cases) | Leaves to Root (Base Cases up to Target) |
| Implementation | Recursion + Cache (Hash Map or Array) | Iterative for loops + Array table |
| Subproblem Coverage | Computes only reachable subproblems | Computes all table states in sequence |
| Space Optimization | Difficult to reduce space complexity | Often reducible from $O(n)$ to $O(1)$ space |
| Stack Overflow Risk | Yes, if recursion depth exceeds system limit | Zero risk; pure iterative execution |
When faced with any DP question in an interview, follow this structured blueprint:
dp[i] (or dp[i][j]) represent in plain English?dp[i] depend on previous states (e.g., dp[i-1], dp[i-2])?dp[0] = 0, dp[1] = 1)?Problem: You are climbing a staircase with $n$ steps. Each time you can climb either 1 or 2 steps. In how many distinct ways can you climb to the top?
Let dp[i] be the number of distinct ways to reach step i.
To reach step i, you could have jumped from step i-1 (by taking 1 step) or from step i-2 (by taking 2 steps): $$\text{dp}[i] = \text{dp}[i-1] + \text{dp}[i-2]$$
dp[1] = 1 (Only 1 way: [1])dp[2] = 2 (2 ways: [1, 1] or [2])| Step ($i$) | Ways from $i-1$ | Ways from $i-2$ | Total Ways dp[i] | Possible Paths |
|---|---|---|---|---|
| 1 | - | - | 1 | (1) |
| 2 | - | - | 2 | (1+1), (2) |
| 3 | dp[2] = 2 | dp[1] = 1 | 3 | (1+1+1), (2+1), (1+2) |
| 4 | dp[3] = 3 | dp[2] = 2 | 5 | All 3 from step 3 + all 2 from step 2 |
| 5 | dp[4] = 5 | dp[3] = 3 | 8 | $5 + 3 = 8$ distinct paths |
| Implementation | Time Complexity | Auxiliary Space Complexity | Call Stack Overhead |
|---|---|---|---|
| Naive Recursion | $O(2^n)$ (Exponential!) | $O(n)$ | Yes |
| Top-Down Memoization | $O(n)$ (Linear) | $O(n)$ (Memo table + Call stack) | Yes |
| Bottom-Up Tabulation | $O(n)$ (Linear) | $O(n)$ (DP array) | No |
| Space-Optimized DP | $O(n)$ (Linear) | $O(1)$ (Only two variables) | No |
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.