dp[i] depends only on dp[i-1] and dp[i-2] → use variables instead of an arraydp[i][j] depends only on row i-1 → use one array instead of a 2D griddp[i][j] depends on row i-1 and i → use two arrays and swap them| Space | Time | |
|---|---|---|
| Before | O(n) | O(n) |
| After | O(1) | O(n) |
| Space | Time | |
|---|---|---|
| Before | O(m × n) | O(m × n) |
| After | O(n) | O(m × n) |
dp[i][j] depends on three cells: dp[i-1][j], dp[i][j-1], and dp[i-1][j-1]. We need to save the diagonal value before overwriting.| Problem | Original | Optimized |
|---|---|---|
| Fibonacci | O(n) | O(1) |
| House Robber | O(n) | O(1) |
| Unique Paths | O(m × n) | O(n) |
| Edit Distance | O(m × n) | O(n) |
| LCS | O(m × n) | O(n) |
| 0/1 Knapsack | O(n × W) | O(W) |