Sub topic 6
Top-Down Solution with Memoization
This chapter assumes you already know the LCS recurrence from the earlier chapters, can read recursive Python functions, and understand why plain recursion repeats work on overlapping subproblems. Here you turn that recurrence into working code and add a cache so each subproblem is solved only once.
From Recurrence to Code
The recurrence works on suffixes. Let solve(i, j) be the LCS length of a[i:] and b[j:]. It follows three rules:
- If either suffix is empty, the answer is 0.
- If
a[i] == b[j], that character belongs to an LCS, so the answer is1 + solve(i + 1, j + 1). - Otherwise, skip one character from either string and take the better result:
max(solve(i + 1, j), solve(i, j + 1)).
Memoization means storing each result the first time you compute it and returning the stored value on later calls. Python's functools.lru_cache does this 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")) # 4How the Cache Changes the Work
Without the cache, the two branches in the mismatch case grow into an exponential call tree. With the cache, each distinct pair (i, j) runs its body at most once. There are at most (m + 1) * (n + 1) such pairs, and each body does a constant amount of work apart from its recursive calls. The total time is therefore O(mn).
Design Choices That Matter
The cached function takes two integer indices. It does not take the strings themselves. This choice has three effects:
- Cache keys are small and cheap to hash. Passing slices such as
a[i:]would copy and hash a string on every call, which adds O(m + n) work per call. - The cache holds at most
(m + 1) * (n + 1)entries. aandbcan be lists, which are unhashable, because the inner function reads them from the enclosing scope and never uses them as cache keys.
Defining solve inside lcs_length_memo also gives every call its own cache. The cache is released when the outer call returns. If you put @lru_cache on a module-level function instead, the cache keeps entries from every input it has ever seen.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Base case checks only `i == len(a)` | `IndexError` on `b[j]` | Check both indices |
| Cache keyed on slices | Slow runs and high memory use | Key the cache on indices |
| Module-level `@lru_cache` with string arguments | Memory grows across calls | Use a nested function, or call `cache_clear()` |
| `maxsize` left at the default of 128 | Repeated recomputation, slow runs | Set `maxsize=None` |
Exercise
You call lcslengthmemo on two strings of 700 characters each that share no characters at all. Roughly how deep can the recursion go, and what happens with Python's default settings?
Show answer
With no matches, each call advances only i or only j, so a path can be up to 700 + 700 = 1400 calls deep. That is above the default limit of about 1000, so Python raises RecursionError. The bottom-up table avoids this because it uses no recursion.
Exercise
Why does solve take integer indices instead of the suffix strings a[i:] and b[j:]?
Show answer
Indices are cheap to hash and need no copying, and they keep the cache to at most (m+1)(n+1) entries. Passing suffixes would copy and hash a string on every call, which adds O(m+n) work per call. Indices also let a and b be unhashable lists.