Sub topic 5
Overlapping Subproblems: Why Dynamic Programming Applies
This chapter assumes you can read recursive Python, know Big-O notation, and have seen the LCS recurrence from the previous chapter. In that recurrence, solve(i, j) is the LCS length of the suffixes a[i:] and b[j:]:
- If either suffix is empty, the answer is 0.
- If
a[i] == b[j], the answer is1 + solve(i + 1, j + 1). - Otherwise, the answer is
max(solve(i + 1, j), solve(i, j + 1)).
Optimal substructure tells us the recurrence gives the right answer. It says nothing about speed. Dynamic programming pays off when a problem also has overlapping subproblems. That means the recursion asks the same question many times.
Watching the Repeats Happen
When the characters differ, the recurrence branches into two calls. Each of those calls can branch again, and the branches meet.
Calling solve(1, 1) twice means its entire subtree is also computed twice, and every repeat lower down multiplies the waste. You can measure this by counting calls in the naive recursion:
from collections import Counter
calls = Counter()
def lcs_naive(a, b, i=0, j=0):
calls[(i, j)] += 1
if i == len(a) or j == len(b):
return 0
if a[i] == b[j]:
return 1 + lcs_naive(a, b, i + 1, j + 1)
return max(lcs_naive(a, b, i + 1, j), lcs_naive(a, b, i, j + 1))
for a, b in [("ABCBDAB", "BDCABA"), ("ABCDEFGHIJ", "KLMNOPQRST")]:
calls.clear()
length = lcs_naive(a, b)
total = sum(calls.values())
distinct = len(calls)
print(f"{a} vs {b}: LCS={length}, total calls={total}, distinct={distinct}")Run it. The second pair has no characters in common, so every call is a mismatch and branches. That is the worst case. The total number of calls grows far faster than the number of distinct (i, j) pairs.
Counting the Distinct Subproblems
Each subproblem is identified by two integers: 0 <= i <= m and 0 <= j <= n. That gives at most (m + 1)(n + 1) distinct subproblems. The number of calls is a different matter. In the all-mismatch case it satisfies T(m, n) = 1 + T(m-1, n) + T(m, n-1), which works out to 2 * C(m+n, m) - 1. That count is exponential.
| Strings (m = n) | Distinct subproblems | Naive calls (no matches) |
|---|---|---|
| 3 | 16 | 39 |
| 10 | 121 | 369,511 |
| 20 | 441 | about 2.76 × 10¹¹ |
The gap between the two columns is the work dynamic programming removes. If each distinct subproblem is solved once and its answer is stored, the total work becomes proportional to (m + 1)(n + 1).
Common Errors
- Caching on the wrong key. If the key holds slices such as
a[i:]instead of indices, every lookup copies and hashes strings. Use the integer pair(i, j). - Testing only on similar strings. Inputs with many matches follow the diagonal branch and look fast. Time the no-match case to see the real worst case.
- Assuming any recursion overlaps. Before adding a cache, check that two different call paths can reach the same arguments.
The next two chapters use this overlap in two ways: caching calls top-down and filling a table bottom-up.
Exercise
For two strings of length 3 with no characters in common, how many calls does the naive recursion make, and how many of them are distinct subproblems?
Show answer
The call count is 2 C(6, 3) - 1 = 2 20 - 1 = 39 calls. The distinct subproblems are the (3 + 1)(3 + 1) = 16 index pairs, so 23 of the 39 calls repeat work already done.
Exercise
Why does the input ("AAAA", "AAAA") make the naive recursion fast even without caching?
Show answer
Every comparison matches, so each call makes exactly one recursive call, solve(i+1, j+1). The recursion is a single chain of 5 calls with no branching, so no subproblem is ever reached twice.