Sub topic 7
Counting states and work per state
This chapter assumes you can read Big-O notation, write recursive functions in Python, and follow the memoized and tabulated Fibonacci code from the earlier chapters. You will learn one method for estimating the cost of almost any dynamic programming (DP) solution.
The core formula
A DP solution computes each distinct subproblem, called a state, at most once. That gives a simple rule:
- Time = (number of distinct states) × (work done per state, not counting the work done inside recursive calls or table lookups)
- Space = (number of states stored) + (any extra memory, such as the recursion stack)
To count states, list every value each state parameter can take and multiply the counts together. To find the work per state, look at the recurrence. If it combines two earlier entries, the work is O(1). If it loops over k choices, the work is O(k).
Seeing the difference in calls
The formula explains why memoization helps. Naive recursion can reach the same state many times. Memoization caps the number of evaluations at the number of states. You can count calls to check this:
from functools import lru_cache
naive_calls = 0
memo_calls = 0
def fib_naive(n):
global naive_calls
naive_calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
@lru_cache(maxsize=None)
def fib_memo(n):
global memo_calls
memo_calls += 1
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
for n in (10, 20, 25):
naive_calls = 0
memo_calls = 0
fib_memo.cache_clear()
fib_naive(n)
fib_memo(n)
print(f"n={n}: naive={naive_calls}, memoized={memo_calls}")The output is:
n=10: naive=177, memoized=11
n=20: naive=21891, memoized=21
n=25: naive=242785, memoized=26The memoized function body runs exactly n + 1 times, once for each state from 0 to n. Each body does O(1) work, so the total time is O(n). Calls that hit the cache never reach the body, and each of those costs O(1).
Applying it to the tutorial's problems
| Problem | State | Number of states | Work per state | Time | Table space |
|---|---|---|---|---|---|
| Fibonacci | n | n + 1 | O(1) | O(n) | O(n) |
| Coin change | amount a | amount + 1 | O(k) for k coins | O(amount · k) | O(amount) |
| LCS | (i, j) | (m + 1)(n + 1) | O(1) | O(m · n) | O(m · n) |
| 0/1 knapsack | (item, capacity) | (items + 1)(W + 1) | O(1) | O(items · W) | O(items · W) |
Coin change is the case where the work per state matters. Each amount loops over every coin, so the time is not O(amount).
Common errors
Ignoring the loop inside a state
Suppose the recurrence is dp[i] = min(dp[j] + cost(j, i) for j in range(i)). There are n states, but state i does O(i) work, so the total is O(n²). If you count only the states, you will report O(n), which is wrong.
Forgetting the recursion stack
A memoized solution stores its cache and also keeps a call stack. For Fibonacci, the stack reaches depth n, which is still O(n) space. However, Python's default recursion limit is about 1000, so fib_memo(5000) raises RecursionError even though its complexity is fine.
Treating pseudo-polynomial as polynomial
Knapsack's O(items · W) depends on the numeric value of the capacity W, not on how many digits it takes to write W. When W = 10⁹, the table has a billion columns per row. This is called pseudo-polynomial time.
Hidden key costs
lru_cache and dictionary memos hash their keys on every lookup. With tuple or string keys, each lookup costs more than O(1). If a key holds a whole slice of the input, the per-state cost grows with the length of that slice.
Exercise
A memoized function lcs(i, j) compares strings of lengths m and n, and each call does O(1) work besides its recursive calls. What are its time complexity, its cache space, and its maximum recursion depth?
Show answer
There are (m + 1)(n + 1) states with O(1) work each, so time is O(m·n) and cache space is O(m·n). Each recursive call decreases i, j, or both, so the stack depth is at most m + n.
Exercise
dp[i] is the length of the longest increasing subsequence ending at index i, computed as 1 + max(dp[j]) over all j < i with a[j] < a[i]. For an array of length n, what are the time and space complexity?
Show answer
There are n states, and state i scans up to i earlier entries, so the time is O(1 + 2 + ... + n) = O(n²). The table uses O(n) space.