Sub topic 6
Top-Down Solution with Memoization
This chapter turns the LCS recurrence into working Python code. You cache each subproblem so it is solved only once. It assumes you know basic Python functions and dictionaries, recursion with base cases, and Big-O notation. It also assumes you have seen the recurrence from the earlier chapter. Here it is again, written with suffix indices:
L(i, j) = 0ifi == len(a)orj == len(b)L(i, j) = 1 + L(i + 1, j + 1)ifa[i] == b[j]L(i, j) = max(L(i + 1, j), L(i, j + 1))otherwise
L(i, j) is the LCS length of the suffixes a[i:] and b[j:]. The answer is L(0, 0).
The Working Model
Memoization is a technique where a recursive function stores each result it computes, keyed by its arguments. When the same arguments come up again, it returns the stored value instead of recomputing it. You keep the shape of the recurrence and add a cache in front of it.
Two facts make this work for LCS:
- The result of
L(i, j)depends only oniandj, because the strings never change during one computation. That makes(i, j)a complete cache key. - There are only
(m + 1) * (n + 1)possible keys, wherem = len(a)andn = len(b). Even if the call tree is exponentially large, the number of distinct calls that do real work is bounded by that product.
The Standard Library Version
Python's functools.lru_cache handles the caching for you:
from functools import lru_cache
def lcs_length_memo(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))
return solve(0, 0)
print(lcs_length_memo("ABCBDAB", "BDCABA")) # 4The design choices here are deliberate:
solveis a nested function. Each call tolcs_length_memocreates a newsolvewith its own empty cache. When the outer call returns, the cache is freed along with the inner function.solvetakes only integer indices. The stringsaandbcome from the enclosing scope, so they are not part of the key.maxsize=Noneturns off eviction. A bounded cache could evict entries that are needed later, which brings back repeated work.
The Explicit Dictionary Version
Writing the cache by hand shows exactly what lru_cache does. It also makes it easy to inspect or reuse the memo table:
def lcs_length_dict(a, b):
memo = {}
def solve(i, j):
if i == len(a) or j == len(b):
return 0
key = (i, j)
if key in memo:
return memo[key]
if a[i] == b[j]:
result = 1 + solve(i + 1, j + 1)
else:
result = max(solve(i + 1, j), solve(i, j + 1))
memo[key] = result
return result
return solve(0, 0)
print(lcs_length_dict("ABCBDAB", "BDCABA")) # 4Base cases are not stored here because they are cheap to recompute. Every non-base result is written to memo before it is returned. That is the only rule a correct memoized function must follow.
The flowchart below traces the calls for a = "AB" and b = "CD". These strings share no characters, so every non-base call branches two ways.
In this tiny example, the cache saves one subtree. On longer strings with few matches, the saved subtrees hold most of the work in the exponential call tree.
Measuring the Effect
You can count how often the function body runs, with and without the cache:
from functools import lru_cache
def count_calls(a, b, use_cache):
calls = 0
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))
if use_cache:
solve = lru_cache(maxsize=None)(solve)
value = solve(0, 0)
return value, calls
a, b = "ABCDEFGHIJKL", "MNOPQRSTUVWX"
print("naive:", count_calls(a, b, use_cache=False))
print("memo: ", count_calls(a, b, use_cache=True))Rebinding solve to its cached wrapper works because the recursive calls look up the name solve in the enclosing scope when they run, so they also go through the cache. With two 12-character strings that share nothing, the naive count runs into the millions. The memoized count can never exceed 13 * 13 = 169, one execution per distinct (i, j) pair. Add a few characters to each string and the naive version becomes impractically slow, while the memoized one barely changes.
When you use lru_cache, you can also call solve.cache_info() inside the outer function to see hits, misses, and the current cache size.
Only Reachable States Are Visited
Top-down evaluation computes only the subproblems that the recursion actually reaches. When a[i] == b[j], the recurrence goes diagonally and never asks for L(i + 1, j) or L(i, j + 1) from that state. The recurrence chapter showed that taking the match is always safe, which is why skipping those calls is correct.
The effect depends on the input:
| Input pair | States visited by memoization | Cells in a full table |
|---|---|---|
| Identical strings of length n | n + 1 | (n + 1)² |
| No shared characters, lengths m and n | about (m + 1)(n + 1) | (m + 1)(n + 1) |
| Typical text with some matches | between the two extremes | (m + 1)(n + 1) |
Memoization never does more work in states than the full table. Each cache lookup does cost more than reading an array cell, though, because it involves a function call, tuple hashing, and a dictionary probe. On dense inputs this overhead often makes the top-down version several times slower than the bottom-up loop in the next chapter, even though both are O(mn).
Common Errors
Recursion depth
At state (i, j) the call stack holds at least about i + j frames, because every step in the mismatch case adds 1 to exactly one index. The deepest state, near (m - 1, n - 1), therefore needs roughly m + n frames. Python's default recursion limit is 1000, so two unrelated strings of 600 characters each raise RecursionError.
If you need top-down code on long inputs, run it in a thread that has a larger stack:
import sys
import threading
def run_with_big_stack(fn, *args, limit=200_000, stack_mb=256):
result = {}
def target():
sys.setrecursionlimit(limit)
result["value"] = fn(*args)
old_size = threading.stack_size(stack_mb * 1024 * 1024)
try:
t = threading.Thread(target=target)
t.start()
t.join()
finally:
threading.stack_size(old_size)
return result["value"]
print(run_with_big_stack(lcs_length_memo, "A" * 3000, "B" * 3000)) # 0threading.stack_size only affects threads created after the call, so the original size is restored once the thread has started. Switching to the bottom-up table is usually the better fix, because it has no recursion at all.
Caching on the wrong key
- Slicing instead of indexing. A version written as
solve(a[1:], b[1:])returns correct answers, but every call copies a string and the cache keys are whole strings. Each key costs O(m + n) to create and hash, which adds a factor ofm + nto both time and memory. - Unhashable arguments. Calling a function decorated with
lru_cachewith a list raisesTypeError: unhashable type: 'list'. Convert the input withtuple(seq)first, or keep the sequences outside the key as the nested version does. - A cache that outlives its input. If you decorate a module-level
solve(i, j)that reads global strings, or creatememo = {}at module level, results from one pair of strings carry over to the next pair. The answers are silently wrong. Make the cache local to one computation.
Forgetting to store or check the result
If the code checks memo but never writes to it, or writes after an early return, you get the naive exponential algorithm. It still returns the right value, so tests on small inputs pass. A call counter like the one above catches this bug quickly.
Complexity at a Glance
Each of the at most (m + 1)(n + 1) states does O(1) work apart from its recursive calls. Total time is therefore O(mn). Space is O(mn) for the cache plus O(m + n) for the call stack. A later chapter covers these costs in detail and compares them with the bottom-up approach.
Exercise
How many distinct (i, j) states does lcslengthmemo evaluate, counting the base case, when a and b are the same string of length n? Why is this far fewer than the size of a full DP table?
Show answer
It evaluates n + 1 states: (0, 0), (1, 1), ..., (n, n). Every comparison matches, so each call makes only the diagonal call and never branches. A full table fills all (n + 1)² cells whether or not they are needed.
Exercise
lcslengthmemo("A" 1500, "B" 1500) raises RecursionError under Python's default limit. Explain why, and estimate the maximum stack depth.
Show answer
No characters match, so every call adds 1 to exactly one index, and the stack depth at state (i, j) is about i + j + 1. The recursion eventually reaches states near (1499, 1499), so the depth approaches 3000 frames. That is far above the default limit of 1000.
Exercise
A teammate moves memo = {} to module level so that "repeated calls are faster." What goes wrong when the function is called with ("ABC", "AC") and then with ("XYZ", "XZ")?
Show answer
The second call finds memo[(0, 0)] = 2 left over from the first pair and returns it. The cache key (i, j) identifies a subproblem only for one fixed pair of strings. In this case the stale value happens to be correct, but for pairs like ("ABC", "AC") followed by ("XYZ", "QQ") it returns 2 instead of 0. The cache must be local to each computation, or the key must include the strings.
Exercise
Rewrite solve so it takes suffix strings, solve(s, t), instead of indices, while still using lru_cache. It returns correct results. What does it cost in time and memory compared with the index version?
Show answer
There are still O(mn) distinct suffix pairs. Each call builds new slices and hashes strings of length up to m + n, so each state costs O(m + n) instead of O(1). Time grows to about O(mn(m + n)), and the cache stores its string keys, so memory grows to about O(mn(m + n)) as well.