Sub topic 9
Analyzing Time and Space Costs
This chapter assumes you have read the earlier chapters on the LCS recurrence, the memoized solution, the bottom-up table, and traceback. It also assumes you can read Big-O notation and run Python 3 code. The goal is to count exactly what each approach costs, find out where the hidden costs are, and see which limit you will run into first on real inputs.
Throughout, m and n are the lengths of the two input sequences a and b.
The Cost Model: States Times Work per State
Every dynamic programming analysis comes down to one product:
- Number of distinct subproblems (states). For LCS, a state is a pair
(i, j)with0 ≤ i ≤ mand0 ≤ j ≤ n. That gives(m + 1)(n + 1)states. - Work per state, not counting the recursive calls. Each state makes one character comparison and then either one addition or one
maxof two values. That is O(1).
Total time is therefore O(mn). Space is the memory that holds the stored states, plus any bookkeeping such as the call stack.
Brute force has no such bound. It checks each of the 2^m subsequences of a against b in O(n) time, which costs O(n · 2^m). Going from 20 to 40 characters multiplies that work by about a million. The DP approach only multiplies its work by 4.
Bottom-Up Tabulation: Predictable and Tight
The table version fills every cell exactly once:
- Time:
m · ninner-loop iterations, each O(1), so Θ(mn). The work is the same whatever the inputs contain. - Space: the full
(m + 1) × (n + 1)table, so Θ(mn). - Traceback: each step decreases
i,j, or both, so it takes at mostm + nsteps. That is O(m + n) time, which is negligible next to filling the table.
The following script shows the quadratic growth. When n doubles, the runtime should grow by about four times.
import time
def lcs_length_table(a, b):
m, n = len(a), len(b)
dp = [[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]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
for n in (500, 1000, 2000):
a = "AB" * (n // 2)
b = "BA" * (n // 2)
start = time.perf_counter()
lcs_length_table(a, b)
elapsed = time.perf_counter() - start
print(n, f"{elapsed:.3f}s")Your absolute times will vary by machine, but the ratio between rows should stay close to 4.
Top-Down Memoization: Same Bound, Different Profile
The memoized version also has an O(mn) worst case, because no state is computed twice. In practice it differs from the table in three ways.
It only visits reachable states
Memoization computes only the states the recursion actually reaches. When the inputs are very similar, the recursion mostly follows the diagonal and skips most of the table. When they share nothing, it reaches nearly every state.
from functools import lru_cache
def memo_states(a, b):
@lru_cache(maxsize=None)
def solve(i, j):
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, solve.cache_info().currsize
print(memo_states("ABCDEFGH", "ABCDEFGH")) # (8, 9) only the diagonal
print(memo_states("AAAAAAAA", "BBBBBBBB")) # (0, 80) all states but (8, 8)With identical strings, the memo stores 9 entries where the table would fill 81 cells. With disjoint alphabets, it stores 80. So memoization is output-sensitive in practice, but its worst case does not improve.
The constant factors are much larger
Each memoized state costs a Python function call, a tuple key built from (i, j), a hash lookup, and a dictionary entry. A table cell costs one indexed store into a list. In CPython, a list slot is an 8-byte pointer, and small integers are shared objects. A cache entry costs well over 100 bytes once you count the key tuple and the dictionary's own overhead. Expect the memoized version to run several times slower than the table and to use roughly an order of magnitude more memory per state.
It uses the call stack
Every call to solve increases i, j, or both, so a chain of nested calls can be up to m + n deep. Stack space is O(m + n). That sounds small, but CPython's default recursion limit is 1000.
Where Memory Runs Out
Time is rarely the first limit you hit. Memory is. Here is the table's footprint for 1000 × 1000:
import tracemalloc
def table_bytes(m, n):
tracemalloc.start()
dp = [[0] * (n + 1) for _ in range(m + 1)]
current, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current
print(f"{table_bytes(1000, 1000) / 1e6:.1f} MB") # about 8 MBAt about 8 bytes per cell, the table size grows like this:
| Input sizes (m × n) | Cells | Approx. table memory (CPython lists) |
|---|---|---|
| 1,000 × 1,000 | 10^6 | 8 MB |
| 10,000 × 10,000 | 10^8 | 800 MB |
| 100,000 × 100,000 | 10^10 | 80 GB |
Two 10,000-line files are an ordinary diff input. At that size the full table is already too large for many laptops. In pure Python, the 10^8 inner-loop iterations also take on the order of a minute. A compact array type such as array('i') or a NumPy array cuts memory to 4 bytes per cell or less. The growth is still quadratic, though, so this only buys a constant factor.
Summary of Costs
| Approach | Time | Extra space | Recovers the subsequence? | Main risk |
|---|---|---|---|---|
| Brute force | O(n · 2^m) | O(m) | Yes | Exponential time |
| Memoization | O(mn) worst case, often less | O(mn) cache + O(m + n) stack | Yes, with extra work | Recursion limit, high per-state overhead |
| Tabulation + traceback | Θ(mn) + O(m + n) | Θ(mn) | Yes | Quadratic memory |
| Two rows (next chapter) | Θ(mn) | O(min(m, n)) | No | No table to trace back through |
| Hirschberg (later chapter) | O(mn), about 2× the work | O(m + n) | Yes | More complex code |
The table splits the costs into two kinds. You cannot avoid the O(mn) time, but the O(mn) space only exists to support traceback. The next chapters exploit that: computing the length needs only the previous row, and Hirschberg's method recovers the subsequence while keeping space linear.
Is O(mn) the Best Possible?
For general inputs, essentially yes. Abboud, Backurs, and Vassilevska Williams (2015) showed that an O(n^(2−ε)) algorithm for LCS would refute the Strong Exponential Time Hypothesis, a widely believed conjecture in complexity theory. Faster algorithms exist only in special cases or for logarithmic gains:
- Hunt–Szymanski runs in O((r + n) log n), where
ris the number of matching position pairs. It is fast when matches are rare, as with lines in source files, and slow whenrapproachesmn. - Masek–Paterson (the "Four Russians" technique) runs in O(n² / log n) over a fixed alphabet.
- Bit-parallel methods process one row in about n / w machine-word operations, where w is the word size, for example 64.
Exercise
The memoized LCS is called on a = "X" 300 and b = "Y" 300. How many cache entries does it create, and what is the maximum recursion depth, approximately? Will it run under CPython's default recursion limit?
Show answer
No characters match, so every state except (300, 300) is reachable: 301 × 301 − 1 = 90,600 entries. Each nested call increases i or j by one, so the depth reaches about m + n = 600 frames. That is under the default limit of 1000, so it runs. At 500 characters each, the depth would be about 1000 and would raise RecursionError.
Exercise
You need only the LCS length of two DNA reads, each 50,000 characters long. Estimate the full-table memory in CPython lists and say which approach you would choose instead.
Show answer
The table has about 50,001² ≈ 2.5 × 10^9 cells. At 8 bytes per cell that is about 20 GB, which is impractical. Only the length is needed, so use the two-row method: about 2 × 50,001 cells, under 1 MB, with the same O(mn) time. For speed, use a compiled or bit-parallel implementation, because 2.5 × 10^9 iterations in pure Python would take hours.
Exercise
Why does traceback not change the overall time complexity of the tabulation approach, even though it is a separate pass?
Show answer
Each traceback step decreases i, j, or both, starting from (m, n), so it takes at most m + n steps of O(1) work. O(m + n) is dominated by the Θ(mn) table fill, so the total stays Θ(mn).