Dynamic Programming Time Complexity: Counting States and Work
Once you can write a dynamic programming solution, the next question is how fast it is. Fortunately there is one rule that covers almost every DP you will meet:
time = number of states x work per state
A state is one subproblem, one cell of the table or one distinct set of arguments to the memoized function. The work per state is what it costs to compute that cell from cells already known, usually a loop over the choices. Space is the number of states you keep at once. This guide applies the rule to four classic problems, with code you can run, and shows where the rule needs care: pseudo-polynomial bounds and recursion depth. If DP itself is new, start with dynamic programming explained.
Examples use Python 3.10 or later and only the standard library.
A warm-up: Fibonacci
Memoized Fibonacci has n + 1 states, fib(0) to fib(n), and each one adds two stored numbers: O(1) work. So it runs in O(n) x O(1) = O(n). The naive recursion has the same states but recomputes them, which is why it is exponential; the rule applies only once each state is computed once.
Coin change: fewest coins
Given k coin values and a target amount, best[a] is the fewest coins that make amount a. Computing best[a] tries every coin as the last coin: best[a] = 1 + min(best[a - c]).
- States: amount + 1 (one per amount from 0 to the target).
- Work per state: k (one check per coin).
- Time O(k x amount), space O(amount).
The code counts the inner-loop steps to show the rule is literal:
def min_coins(coins, amount):
inf = float("inf")
best = [0] + [inf] * amount
work = 0
for a in range(1, amount + 1): # amount states
for c in coins: # len(coins) work per state
work += 1
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
return best[amount], work
print(min_coins([1, 3, 4], 6))
print(min_coins([1, 5, 10, 25], 100))
print(min_coins([2], 7))
(2, 18)
(4, 400)
(inf, 7)
Each pair is (answer, steps). Amount 6 with 3 coins takes 6 x 3 = 18 steps; amount 100 with 4 coins takes 400; amount 7 with only a 2-cent coin takes 7 steps and correctly reports that it cannot be done (infinity).
Longest common subsequence
A subsequence keeps characters in order but may skip some. The longest common subsequence (LCS) of two strings a and b, of lengths m and n, is the longest string that is a subsequence of both.
The state t[i][j] is the LCS length of the first i characters of a and the first j characters of b. If a[i - 1] equals b[j - 1], that character extends the LCS of the two shorter prefixes: t[i][j] = t[i - 1][j - 1] + 1. Otherwise one of the two characters is not used, so t[i][j] = max(t[i - 1][j], t[i][j - 1]).
- States: (m + 1)(n + 1).
- Work per state: O(1), one comparison and a max.
- Time O(mn), space O(mn) for the full table.
def lcs_table(a, b):
m, n = len(a), len(b)
t = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
t[i][j] = t[i - 1][j - 1] + 1
else:
t[i][j] = max(t[i - 1][j], t[i][j - 1])
# walk back from the corner to recover one subsequence
i, j, out = m, n, []
while i and j:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i, j = i - 1, j - 1
elif t[i - 1][j] >= t[i][j - 1]:
i -= 1
else:
j -= 1
return t[m][n], "".join(reversed(out))
def lcs_two_rows(a, b):
if len(b) > len(a):
a, b = b, a # keep the rows as short as possible
prev = [0] * (len(b) + 1)
for x in a:
cur = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
cur[j] = prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
print(lcs_table("ABCBDAB", "BDCABA"))
print(lcs_two_rows("ABCBDAB", "BDCABA"))
(4, 'BCBA')
4
"BCBA" is one LCS of length 4; there are others of the same length. The walk back from the bottom-right corner, which recovers the actual subsequence, needs the full table.
Cutting space with two rows
Each row of the table reads only the row above it. If you need only the length, keep two rows and swap them: lcs_two_rows uses O(min(m, n)) space by making the shorter string the row. The time is still O(mn), because the number of states computed has not changed; only the number kept at once has. The same rolling-row trick applies to edit distance, grid paths and most DPs whose recurrence looks back a fixed number of rows. Recovering the subsequence itself in linear space is possible but needs a more elaborate divide-and-conquer method.
0/1 knapsack and pseudo-polynomial time
You have n items, each with a value and a weight, and a capacity W. Choose items, each at most once, to maximize total value without exceeding W. The state best[c] is the highest value achievable with capacity c using the items processed so far. For each item, every capacity from W down to the item's weight is updated: either skip the item, or take it and add its value to best[c - weight]. Going downward ensures each item is used at most once.
- States: n x (W + 1), item by capacity.
- Work per state: O(1), a max of two options.
- Time O(nW), space O(W) with the one-dimensional array shown.
def knapsack(items, W):
best = [0] * (W + 1) # best[c] = max value with capacity c
for value, weight in items: # n items
for c in range(W, weight - 1, -1): # W + 1 capacities, downward
best[c] = max(best[c], best[c - weight] + value)
return best[W]
items = [(60, 10), (100, 20), (120, 30)]
print(knapsack(items, 50))
print(knapsack(items, 1000))
220
280
With capacity 50 the optimum is 220 (the items of weight 20 and 30). With capacity 1000 all three fit, for 280, but the loop now runs over a thousand capacities per item instead of fifty.
O(nW) looks polynomial, and it is polynomial in the value W. But running time is measured against the size of the input, and writing W down takes only about log2(W) bits. If W has b bits, W can be as large as 2^b, so O(nW) is O(n x 2^b): exponential in the number of bits of W. An algorithm like this is called pseudo-polynomial. It is fast when W is small, say in the thousands, and useless when the weights are 60-bit numbers. This is consistent with the decision version of knapsack being NP-complete; see P vs NP and NP-completeness. Coin change's O(k x amount) is pseudo-polynomial for the same reason.
Edit distance
The edit distance between two strings is the fewest single-character insertions, deletions and replacements that turn one into the other. The state d[i][j] is the edit distance between the first i characters of a and the first j characters of b. The last step was a deletion, an insertion, or a replacement (free if the characters already match), so d[i][j] is the minimum of three neighbors plus their cost. The base cases are the first row and column: turning a prefix into the empty string takes one deletion per character.
- States: (m + 1)(n + 1).
- Work per state: O(1), a min of three.
- Time O(mn), space O(mn), or O(min(m, n)) for the distance alone with two rows.
def edit_distance(a, b):
m, n = len(a), len(b)
d = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
d[i][0] = i # delete all of a[:i]
for j in range(n + 1):
d[0][j] = j # insert all of b[:j]
for i in range(1, m + 1):
for j in range(1, n + 1):
same = a[i - 1] == b[j - 1]
d[i][j] = min(d[i - 1][j] + 1, # delete
d[i][j - 1] + 1, # insert
d[i - 1][j - 1] + (not same)) # replace or match
return d[m][n]
print(edit_distance("kitten", "sitting"))
print(edit_distance("", "abc"), edit_distance("same", "same"))
3
3 0
"kitten" to "sitting" takes 3 edits: replace k with s, replace e with i, and insert g. The empty string needs 3 insertions to become "abc", and identical strings need none.
When the work per state is not constant
Every example above does O(1) work per state, so time equals the number of states. That is not always true, and it is the most common way to get a DP bound wrong. Some examples:
| Problem | States | Work per state | Time |
|---|---|---|---|
| Fibonacci | n | O(1) | O(n) |
| Coin change, k coins | amount | O(k) | O(k x amount) |
| LCS, edit distance | mn | O(1) | O(mn) |
| 0/1 knapsack | nW | O(1) | O(nW), pseudo-polynomial |
| Longest increasing subsequence, simple DP | n | O(n), scan all earlier items | O(n^2) |
| Matrix-chain order, interval DPs | n^2 (one per interval) | O(n), try every split point | O(n^3) |
To read a DP's cost, find the loops: the outer loops enumerate states, and any loop inside the cell computation is work per state.
Memoized recursion: same time, extra stack
A memoized recursive solution computes each state once, just like the table, so it has the same time bound. It also computes only the states it actually reaches, which can be fewer. The difference is space: besides the cache, it uses call-stack depth equal to the longest chain of dependencies, and in Python that chain is capped by the recursion limit.
import sys
from functools import cache
def lcs_memo(a, b):
@cache
def go(i, j):
if i == len(a) or j == len(b):
return 0
if a[i] == b[j]:
return 1 + go(i + 1, j + 1)
return max(go(i + 1, j), go(i, j + 1))
return go(0, 0)
print("recursion limit:", sys.getrecursionlimit())
for size in (300, 600):
try:
print(size, lcs_memo("A" * size, "B" * size))
except RecursionError:
print(size, "RecursionError")
recursion limit: 1000
300 0
600 RecursionError
For two strings with no common character, the recursion first walks i all the way to the end, then j, so the depth reaches about m + n. With 300 characters each that is about 600 frames, under the limit; with 600 each it is about 1,200, and Python raises RecursionError. The table version of the same LCS has no such limit. When inputs can be large, prefer the bottom-up form, rather than raising the recursion limit.
Reading the tools
The Interview Complexity Estimator has a "2-D dynamic programming" row that it maps to O(n²) time and O(n²) space, which matches filling an n by n table with constant work per cell, such as LCS or edit distance on two strings of length n. For m and n of different sizes, the honest bound is O(mn), and for knapsack it is O(nW), which the rules table cannot express. The estimator labels 2-D DP "Hard" in its large regime, a site heuristic for quadratic or worse at large n, not a statement about any particular problem.
To see what quadratic means in numbers, the Big O Complexity Analyzer evaluates n^2 at n = 1000 as 1,000,000 and at n = 10,000 as 100,000,000. An O(mn) table for two 10,000-character strings has that many cells, which is a reason to keep only two rows when you can.
Check yourself
- A DP has states (i, j) with 0 <= i, j < n, and computing each one loops over k from i to j. What is the time? (n^2 states x O(n) work = O(n^3).)
- Knapsack with n = 100 items and W = 10^9. Is O(nW) practical? (No: about 10^11 steps, even though n is small.)
- You switch the LCS table to two rows. What changes, and what does not? (Space drops to O(min(m, n)); time stays O(mn); you can no longer walk back to recover the subsequence.)