Sub topic 7
Counting states and work per state
This chapter assumes you can read Big-O notation, write a recursive function in Python, and recognize the memoized and tabulated Fibonacci functions from the previous chapters. Here you will learn one method for estimating the cost of any dynamic programming solution before you run it, and how to find the hidden costs that the method can miss.
The core formula
Every DP solution solves a set of distinct subproblems called states. Each state is solved by combining the answers of a few other states, called its transitions. If each state is solved exactly once, the running time is:
time = (number of states) × (work per state)
Work per state is the cost of computing one entry after its dependencies are known. Usually that means looping over the transitions and doing a constant amount of arithmetic for each one.
Space follows a similar rule:
space = (number of stored states) + (extra memory such as the recursion stack)
The formula holds because memoization and tabulation both guarantee that each state is computed once. Without that guarantee, the naive recursion, the count of distinct states says nothing about the running time. What matters there is the number of calls, which can grow exponentially.
Seeing the difference: calls versus states
You can confirm the formula by counting calls directly. The script below instruments the naive and memoized Fibonacci functions.
calls = 0
def fib_naive(n):
global calls
calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo(n, memo):
global calls
calls += 1
if n < 2:
return n
if n not in memo:
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
for n in (5, 10, 15, 20, 25):
calls = 0
fib_naive(n)
naive_calls = calls
calls = 0
fib_memo(n, {})
memo_calls = calls
print(f"n={n:2d} naive calls={naive_calls:7d} memo calls={memo_calls:3d}")Output:
n= 5 naive calls= 15 memo calls= 9
n=10 naive calls= 177 memo calls= 19
n=15 naive calls= 1973 memo calls= 29
n=20 naive calls= 21891 memo calls= 39
n=25 naive calls= 242785 memo calls= 49The naive version makes 2·F(n+1) − 1 calls, which grows by about a factor of 1.618 for each step in n. The memoized version makes exactly 2n − 1 calls. There are n + 1 states (0 through n), and each state that is computed issues 2 calls. Calls that hit the cache cost O(1) and are counted under the work of the state that made them. So the total is n states × O(1) work = O(n).
Applying the recipe to common problems
The table below applies the recipe to the problems in this tutorial. In each row, the number of states comes from the ranges of the state's parameters, and the work per state comes from the number of choices the recurrence considers.
| Problem | State | Number of states | Work per state | Time | Table space |
|---|---|---|---|---|---|
| Fibonacci | `dp[i]`, 0 ≤ i ≤ n | n + 1 | O(1), two lookups | O(n) | O(n) |
| Coin change (min coins) | `dp[a]`, 0 ≤ a ≤ amount | amount + 1 | O(k), one per coin | O(amount · k) | O(amount) |
| Longest common subsequence | `dp[i][j]`, 0 ≤ i ≤ m, 0 ≤ j ≤ n | (m + 1)(n + 1) | O(1), three lookups | O(m · n) | O(m · n) |
| 0/1 knapsack | `dp[i][c]`, item index and capacity | (n + 1)(W + 1) | O(1), take or skip | O(n · W) | O(n · W) |
Two habits make this work:
- Multiply the parameter ranges. If a state has parameters
iandj, anditakes m values andjtakes n values, there are m · n states. If a third parameter takes k values, multiply again. - Count what the inner loop actually does. In coin change, computing
dp[a]loops over all k coins, so the work is O(k), not O(1). The nested loop structure of a tabulated solution usually shows the cost directly: the outer loops enumerate states and the innermost loop enumerates transitions.
When work per state is not constant
Many recurrences take a minimum or maximum over a range of earlier states, and that range grows with the input. The longest increasing subsequence (LIS) is a standard example. Let dp[i] be the length of the longest increasing subsequence that ends at index i:
def lis_length(a):
n = len(a)
if n == 0:
return 0
dp = [1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
print(lis_length([10, 9, 2, 5, 3, 7, 101, 18])) # 4There are n states, but state i examines i earlier states. The total work is 0 + 1 + … + (n − 1) = n(n − 1)/2, which is O(n²). Writing "n states, so O(n)" would be wrong. When the work varies by state, add it up across states instead of multiplying by a single constant. An upper bound (n states × at most n work) also gives O(n²) here, and it is often good enough.
Space: the table and the stack
The table holds one entry per stored state, so table space usually equals the number of states. Top-down solutions add a second cost, the recursion stack. Its depth is the length of the longest chain of calls that are pending at the same time.
For memoized Fibonacci, fib(n) calls fib(n - 1), which calls fib(n - 2), and so on down to the base case before anything returns. The stack depth is therefore about n. That depth is still O(n), so the Big-O space is unchanged, but it has a practical limit:
from functools import lru_cache
import sys
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(sys.getrecursionlimit()) # usually 1000
try:
fib(5000)
except RecursionError as e:
print("RecursionError:", e)Tabulated solutions use no recursion stack, so their space is just the table. This is one input to the choice between the two styles, which the next chapter covers.
Hidden costs the formula can miss
The formula assumes that looking up a state costs O(1) and that the arithmetic at each state costs O(1). Several common coding patterns break those assumptions.
Expensive state keys
If the state passed to a memoized function is a slice or a string built at each call, every call pays for the copy and for hashing it:
from functools import lru_cache
@lru_cache(maxsize=None)
def lcs_slow(a, b):
if not a or not b:
return 0
if a[0] == b[0]:
return 1 + lcs_slow(a[1:], b[1:])
return max(lcs_slow(a[1:], b), lcs_slow(a, b[1:]))
print(lcs_slow("ABCBDAB", "BDCABA")) # 4The number of distinct states is still (m + 1)(n + 1), because every key is a suffix pair. But each call creates new slices of length up to m and n and then hashes them, so the work per state is O(m + n). The total becomes O(m · n · (m + n)). Passing integer indices i and j instead restores O(1) work per state.
Large numbers
Python integers have no size limit, and the n-th Fibonacci number has about 0.694·n bits. Adding two such numbers costs time proportional to their length. "O(n) time" for Fibonacci counts additions. Measured in bit operations, it is O(n²). This rarely matters for counting problems with small answers, but it does matter when a problem asks for an exact count that grows exponentially. That is why many problems ask for the answer modulo a fixed prime.
Dictionary overhead
A memoization dictionary has O(1) expected lookups, but each lookup costs more than indexing a list: the key is hashed, a bucket is probed, and each entry uses memory for the key, the value, and the table slot. For dense integer states, a list sized to the number of states is faster and smaller. The Big-O is the same, but the constant factor can be several times larger for the dictionary.
Reachable states versus all states
Tabulation fills every entry in the table. Memoization computes only the states that the recursion reaches from the starting state. Sometimes that is far fewer.
Take coin change with coins [5, 10] and amount 1000, solved top-down. Starting from 1000 and subtracting 5 or 10 reaches only multiples of 5, so about 201 states are visited instead of 1001. The worst-case bound O(amount · k) still holds, but the actual count can be lower. When you analyze a top-down solution, the number of states is an upper bound. The real cost depends on how many states are reachable.
Pseudo-polynomial running time
Knapsack runs in O(n · W), which looks polynomial. But W is a number in the input, not the size of the input. A capacity of one billion takes only about 30 bits to write down, yet it creates a billion columns. An algorithm whose running time is polynomial in the numeric value of an input but exponential in the number of bits needed to write it is called pseudo-polynomial. Coin change with a large amount behaves the same way.
The practical test is to estimate the table size before writing code. Multiply the parameter ranges and compare the result with what fits in memory and runs in your time budget. About 10⁷ to 10⁸ simple operations per second is a reasonable rough figure for pure Python. A state count of 10¹⁰ means you need a different state definition, not a faster loop.
Summary of the method
- Write down the state's parameters and the range of each one.
- Multiply the ranges to get the number of states.
- Count the transitions each state examines. If that count varies, add it up across all states.
- Multiply to get the time. Then check for hidden costs: slicing, large keys, and big integers.
- For space, count stored entries and add the maximum recursion depth for top-down code.
Exercise
A memoized function edit(i, j) computes the edit distance between prefixes of strings of length m and n. Each call makes at most three recursive calls and does O(1) other work. State its time complexity, table space, and maximum recursion depth.
Show answer
There are (m + 1)(n + 1) states, each with O(1) work, so time is O(m · n). The memo stores up to (m + 1)(n + 1) entries, so table space is O(m · n). Each recursive call decreases i, j, or both, so the deepest chain has at most m + n calls, giving O(m + n) stack depth.
Exercise
A tabulated solution defines dp[i][j] for 0 ≤ i, j < n, and computes each entry as the minimum over k from i to j of dp[i][k] + dp[k + 1][j] + cost(i, j), where cost is O(1). What is the time complexity, and why is "n² states, so O(n²)" wrong?
Show answer
There are about n² states, but entry (i, j) examines j − i + 1 split points, which is up to n. Summed over all pairs, that is O(n³) time. The n² estimate ignores that the work per state grows linearly with the interval length.
Exercise
A 0/1 knapsack instance has 50 items and capacity 2,000,000,000. Using the full O(n · W) table, estimate the number of entries and say whether the approach is practical in Python.
Show answer
The table has about 51 × 2,000,000,001 ≈ 10¹¹ entries. Even the one-row version needs 2 × 10⁹ entries and about 10¹¹ updates, which would take hours in pure Python and far more memory than is available. The running time is pseudo-polynomial in W, so a different method is needed, such as a state indexed by value instead of weight, or meet-in-the-middle over the 50 items.