Sub topic 9
Analyzing Time and Space Costs
This chapter assumes you know Big-O notation and have read the memoized and tabulated LCS solutions from earlier chapters. Throughout, m = len(a) and n = len(b).
Counting Subproblems
In dynamic programming, the cost usually comes from two numbers: how many distinct subproblems there are, and how much work each one takes.
For LCS, a subproblem is a pair of positions (i, j). i ranges over 0..m and j over 0..n, so there are (m + 1)(n + 1) subproblems. Each one does a constant amount of work. It compares two characters, then either adds 1 to one stored value or takes the max of two. That gives O(mn) time for both the memoized and the tabulated versions.
You can confirm the bound by counting how many times the memoized function actually runs its body:
from functools import lru_cache
def count_states(a, b):
calls = 0
@lru_cache(maxsize=None)
def solve(i, j):
nonlocal calls
calls += 1
if i == len(a) or j == len(b):
return 0
if a[i] == b[j]:
return 1 + solve(i + 1, j + 1)
return max(solve(i + 1, j), solve(i, j + 1))
length = solve(0, 0)
return length, calls
a, b = "ABCBDAB", "BDCABA"
length, calls = count_states(a, b)
print(length, calls, (len(a) + 1) * (len(b) + 1))The second number printed is never larger than the third. Memoization often visits fewer states than the full table holds, because matching characters skip diagonally past some pairs. In the worst case it still visits all of them.
Where the Memory Goes
The two DP versions have the same asymptotic space, O(mn), but their constant factors and failure modes differ:
- Memoization stores a dictionary entry per visited state, which costs much more memory per entry than a list slot. Its recursion can also nest
m + ncalls deep. CPython's default recursion limit is about 1000, so two strings of 600 characters can raiseRecursionErrorwell before memory runs out. - Tabulation uses a plain list of lists and no recursion. Traceback walks from
(m, n)to an edge of the table. Each step decreasesi,j, or both, so it takes at mostm + nsteps. That is O(m + n) added on top of the fill.
For scale, two strings of 10,000 characters need a table of about 10⁸ cells. Each slot in a Python list is an 8-byte pointer, so the table takes roughly 800 MB. The time is manageable, but the memory is usually what makes the full table impractical.
Summary of Costs
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Brute force | O(n · 2^m) | O(m) | Checks each of the 2^m subsequences of `a` against `b` |
| Memoization | O(mn) | O(mn) cache + O(m + n) stack | Can hit the recursion limit |
| Tabulation + traceback | O(mn) + O(m + n) | O(mn) | No recursion, and the full table supports traceback |
Common Mistakes
- Calling the memoized version O(m + n) because "the recursion depth is m + n." Depth bounds the stack, not the total number of calls.
- Forgetting that
lru_cacheholds its entries until the decorated function is garbage-collected. In this code, the function is created fresh on each call, so the cache is freed once the call returns. - Counting traceback as O(mn). It visits one path through the table, not every cell.
Exercise
You must compute the LCS of a 2,000-character string and a 50-character string, and you need the subsequence itself, not just its length. Which approach do you pick, and what are its time cost and table size in cells?
Show answer
Use bottom-up tabulation with traceback. The table has 2,001 × 51 = 102,051 cells, and filling it takes O(mn), about 100,000 constant-time steps. The traceback adds at most 2,050 steps. Memoization risks a RecursionError, because its recursion depth can reach m + n = 2,050, which is above CPython's default limit of about 1000.
Exercise
Why is the brute-force bound O(n · 2^m) rather than O(2^m)?
Show answer
There are 2^m candidate subsequences of a. Checking whether each candidate is also a subsequence of b takes a linear scan of b, which costs O(n).