Ankit KanojiyaAdvanced
Evergreen guide by Ankit Kanojiya · Advanced · DSA
Dynamic Programming: From Recursion to Memoization and Tabulation
A step-by-step path from naive recursion to efficient dynamic programming. Learn to spot overlapping subproblems and convert them into memoized or tabulated solutions.
- Dynamic Programming
- Memoization
- Tabulation
- Recursion
- Optimization
Dynamic programming solves a problem by combining answers to smaller subproblems, storing each answer so it is never recomputed. It applies when a problem has two properties: optimal substructure, meaning an optimal solution is built from optimal solutions to subproblems, and overlapping subproblems, meaning the same subproblem recurs many times. The reliable route is to write the recursion first, then cache it.
Starting From Recursion
The Fibonacci sequence shows the pattern in miniature. The naive recursion is correct but exponential because it recomputes the same values repeatedly.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Computing fib(5) calls fib(3) twice, fib(2) three times, and so on. The call tree has about 2^n nodes, so this is O(2^n) time. The subproblems overlap heavily, which is exactly the signal that dynamic programming will help.
Top-Down Memoization
Memoization keeps the natural recursion but stores each computed answer in a cache. Before computing, it checks whether the answer already exists.
def fib_memo(n, cache=None):
if cache is None:
cache = {}
if n < 2:
return n
if n in cache:
return cache[n]
cache[n] = fib_memo(n - 1, cache) + fib_memo(n - 2, cache)
return cache[n]
Now each value from 0 to n is computed once, so the time drops to O(n) with O(n) space for the cache and the call stack. Memoization is often the quickest conversion because the recursive structure is unchanged; only a lookup and a store are added.
Bottom-Up Tabulation
Tabulation flips the direction. Instead of recursing from the target down, it fills a table from the base cases up, so every value a formula needs is already present.
def fib_tab(n):
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
This removes recursion entirely, avoiding stack limits. Because each entry depends only on the two before it, the table can collapse to two variables and O(1) space.
def fib_constant(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
Recognizing that only a small window of the table is needed is a common optimization once the recurrence is clear.
Defining the State and Transition
Every dynamic programming solution rests on two decisions. The state is what a subproblem is indexed by, such as a position, a remaining capacity, or a pair of indices. The transition is the recurrence that builds a state from smaller states. Writing these explicitly before coding prevents most mistakes.
Consider the 0/1 knapsack problem: choose items with given weights and values to maximize value without exceeding capacity. The state is the best value using the first i items with capacity c. The transition is to either skip item i or take it.
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
w, v = weights[i - 1], values[i - 1]
for c in range(capacity + 1):
dp[i][c] = dp[i - 1][c] # skip item i
if w <= c:
take = dp[i - 1][c - w] + v # take item i
dp[i][c] = max(dp[i][c], take)
return dp[n][capacity]
There are n times capacity states and each is O(1) to fill, so the time is O(n times capacity) and the space is the same, reducible to a single row processed carefully.
A Classic One-Dimensional Example
The longest increasing subsequence asks for the length of the longest strictly increasing run of elements, not necessarily contiguous. The state is the length of the best subsequence ending at index i.
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
Each element looks back at all earlier elements, giving O(n squared) time. A more advanced version using binary search reaches O(n log n), which illustrates that a correct dynamic program is often the first step, not the last.
Memoization or Tabulation
Both reach the same complexity, so the choice is practical:
- Memoization is faster to write from a working recursion and naturally skips states that are never reached.
- Tabulation avoids recursion depth limits and makes space optimization obvious, since the fill order is explicit.
- Tabulation can be marginally faster by avoiding function-call overhead.
A Reliable Method
- Write the brute-force recursion and confirm it is correct.
- Identify the parameters that change between calls; those become the state.
- Add a cache keyed by the state for memoization, or build a table and fill it in dependency order for tabulation.
- Optimize space if each state depends on only a few recent states.
Common Mistakes
- Choosing a state that does not capture everything the transition needs, producing wrong answers.
- Filling a table in an order where a needed entry is not yet computed.
- Forgetting base cases, which corrupts every value built on them.
Following the progression from recursion to a cache keeps dynamic programming approachable even for unfamiliar problems.