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. It uses suffix indices: solve(i, j) is the LCS length of a[i:] and b[j:].
The recurrence alone does not make a fast algorithm. Written as plain recursion, it takes exponential time. Dynamic programming needs a second property besides optimal substructure: the recursion must ask the same questions many times. This chapter shows that the LCS recursion has this property, measures how much repeated work it does, and points out the coding mistakes that hide the repetition.
The Recurrence as Plain Recursion
Here is the recurrence translated directly into code, with no caching:
- 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)).
The mismatch case is where the cost comes from. It makes two recursive calls, and each of those can make two more. When the strings share no characters, every call takes the mismatch branch, so the recursion is a full binary branching process that stops only at the edges.
Where the Repetition Comes From
Take the mismatch case at (i, j). One branch goes to (i + 1, j) and the other to (i, j + 1). If both of those also mismatch, the first branch calls (i + 1, j + 1) by dropping a character from b, and the second branch calls (i + 1, j + 1) by dropping a character from a. Two different paths reach the same subproblem.
With two-character strings, one subproblem is duplicated. As the inputs grow, duplicated subtrees contain more duplicated subtrees, and the repetition compounds. A subproblem deep in the grid can be reached by a very large number of distinct paths, and the naive recursion re-solves it once per path.
The same subproblems drawn as a graph look different. Each distinct (i, j) appears once, and arrows show which subproblems it depends on:
The tree is what the naive code does. The graph is the work that actually needs doing. Dynamic programming gets you from the first to the second.
Measuring It
Counting the calls makes the gap concrete. The function below runs the naive recursion and records how often each (i, j) gets solved.
from collections import Counter
from math import comb
def lcs_naive_counted(a, b):
calls = Counter()
def solve(i, j):
calls[(i, j)] += 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))
length = solve(0, 0)
return length, sum(calls.values()), len(calls), calls
# Worst case: no characters in common, so every call branches.
for k in [1, 3, 5, 8, 10]:
a, b = "A" * k, "B" * k
length, total, distinct, _ = lcs_naive_counted(a, b)
assert total == 2 * comb(2 * k, k) - 1
assert distinct == (k + 1) ** 2 - 1
print(f"k={k:2d} total calls={total:>8,} distinct states={distinct}")
# A realistic pair: which states were recomputed most?
length, total, distinct, calls = lcs_naive_counted("ABCBDAB", "BDCABA")
print("LCS length:", length)
print("total calls:", total, "distinct states:", distinct)
print("most repeated:", calls.most_common(3))The assertions hold exactly. When there are no matches, total calls follow T(p, q) = 1 + T(p-1, q) + T(p, q-1) with T = 1 on the edges. The solution is T(p, q) = 2·C(p+q, p) − 1. Distinct states are every (i, j) in the grid except (m, n), which can be reached only by a diagonal step, and a diagonal step needs a match.
| k (both lengths) | Total naive calls | Distinct subproblems |
|---|---|---|
| 1 | 3 | 3 |
| 5 | 503 | 35 |
| 10 | 369,511 | 120 |
| 15 | 310,235,039 | 255 |
| 20 | 275,693,057,639 | 440 |
The total grows like C(2k, k), which is about 4^k / sqrt(πk). The distinct count grows like k². At length 20 the naive code makes around 600 million calls per distinct subproblem. That ratio is the overlap, and it is the work a cache or table removes.
Overlap Versus Plain Divide and Conquer
Overlap is the difference between dynamic programming and ordinary divide and conquer. Merge sort splits an array into two disjoint halves. Neither half ever asks about the other half's elements, so no subproblem repeats, and caching would gain nothing. LCS shrinks one string or the other, so the subproblems overlap along a grid, and different shrink orders land on the same cell.
| Property | Merge sort | Naive LCS recursion |
|---|---|---|
| Subproblems | Disjoint halves | Overlapping suffix pairs |
| Distinct subproblems | O(n) | O(mn) |
| Calls without caching | O(n) | Exponential in the worst case |
| Benefit of caching | None | Exponential to polynomial |
Before you add a cache, ask two questions. Can you name the state with a small tuple? Does the recursion revisit those tuples? If both answers are yes, dynamic programming applies.
Why the State Must Be Exactly (i, j)
The overlap exists only because the answer for (i, j) depends on nothing except i and j. It does not depend on how the recursion got there or on what has been matched so far. This is the "no hidden state" condition, and three common mistakes break it.
- Carrying the partial answer in the state. A signature like
solve(i, j, matched_so_far)makes each path a different state. The two paths to(1, 1)above would carry different prefixes, so they would never be recognized as the same question. Return the length or subsequence of the remaining suffixes and combine results on the way back up. - Using slices as the state.
solve(a[1:], b[1:])is correct, but every call copies strings, and a cache keyed on string contents hashes long strings on every lookup. Integer indices name the same subproblem in O(1) space. - Mixing prefix and suffix conventions. If some calls treat
ias "first i characters" and others as "from index i onward", equal tuples stand for different subproblems. A cache would then return wrong answers. Pick one convention and write it in a comment.
Counting the Work That Remains
Once each distinct state is solved once, the cost is the number of states times the work per state. There are (m + 1)(n + 1) states. Each one does constant work beyond its recursive lookups: one comparison and at most one max. That is where the O(mn) bound comes from. The next two chapters build it, first by caching the recursion and then by filling the grid in dependency order.
Exercise
For a = "AAAA" and b = "BBB" (no common characters), how many calls does the naive recursion make in total, and how many distinct (i, j) states does it visit?
Show answer
Total calls are 2·C(4+3, 4) − 1 = 2·35 − 1 = 69. Distinct states are (4+1)(3+1) − 1 = 19. Every grid cell except (4, 3) is visited, because (4, 3) can only be reached by a diagonal step, which requires a match.
Exercise
A colleague writes solve(i, j, path) where path is the list of matched characters so far, then adds @lru_cache. The code runs, but it is still exponential on long inputs. Explain why, and fix the design.
Show answer
Including path in the key makes every route to the same (i, j) a different cache entry, so no overlap is ever reused. (lru_cache would also reject a list argument because lists are unhashable. A tuple runs but gets no hits.) Remove path from the state: solve(i, j) should return the LCS of the remaining suffixes, and the caller combines results, for example by prepending a[i] on a match. The cache then has at most (m+1)(n+1) entries.
Exercise
Would adding a cache to a recursive binary search improve its asymptotic running time? Justify using the idea of overlapping subproblems.
Show answer
No. Each call to binary search makes at most one recursive call on a range no other call uses, so no subproblem is ever revisited. The cache would never hit and would only add memory overhead. Caching helps only when different paths reach the same state, as in LCS.