Sub topic 2
Overlapping Subproblems: Why Dynamic Programming Applies
This chapter assumes you know Python lists and functions, recursion, Big-O notation, and the LCS recurrence from the previous chapter.
Overlapping Subproblems
Let solve(i, j) be the LCS length of the suffixes a[i:] and b[j:]. When the characters differ, solve(0, 0) calls both solve(1, 0) and solve(0, 1). Each of those calls solve(1, 1) again. Plain recursion recomputes the same pairs over and over, which costs exponential time. There are only (m+1)(n+1) distinct pairs, so storing each answer once makes the problem tractable.
Top-Down Solution with Memoization
Memoization caches each result the first time it is computed.
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")) # 4A common error is passing long strings to this function. The recursion depth can reach m + n, which can exceed Python's default recursion limit of about 1000.
Bottom-Up Solution with a DP Table
Tabulation fills dp[i][j], the LCS length of the prefixes a[:i] and b[:j], row by row. Row 0 and column 0 stay at 0.
Recovering the Subsequence by Traceback
To recover the subsequence, start at dp[m][n] and walk back. On a match, keep the character and move diagonally. Otherwise, move toward the larger neighbor.
def lcs(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])
out = []
i, j = m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(reversed(out))
result = lcs("ABCBDAB", "BDCABA")
print(result, len(result)) # one LCS of length 4Analyzing Time and Space Costs
| Approach | Time | Extra space |
|---|---|---|
| Plain recursion | O(2^(m+n)) | O(m + n) stack |
| Memoization | O(mn) | O(mn) cache + O(m + n) stack |
| Tabulation + traceback | O(mn) + O(m + n) | O(mn) table |
Exercise
What does lcs("AB", "BA") return, and what would it return if ties moved left (j -= 1) instead of up?
Show answer
It returns "A". At cell (2, 2) the two neighbors tie at 1, so the walk moves up and then matches A. If ties moved left, the walk would match B instead. Both answers are valid LCSs of length 1.