Sub topic 4
Optimal Substructure and the LCS Recurrence
This chapter assumes you are comfortable with recursion and base cases, Python functions and lists, and Big-O notation. You should also know what a subsequence is and why trying every subsequence takes exponential time. Both ideas were covered in earlier chapters.
The goal here is to derive the rule that every LCS algorithm in this tutorial is built on. That rule is a recurrence: it expresses the LCS length of two sequences in terms of the LCS lengths of shorter sequences. Once you have it and can justify every case, memoization and tabulation are just two ways of evaluating it.
Notation: Prefixes
Let X = x1 x2 ... xm and Y = y1 y2 ... yn. Write Xi for the prefix made of the first i elements of X. So X0 is empty and Xm is all of X. Yj is defined the same way.
Define c(i, j) as the length of an LCS of Xi and Yj. The answer we want is c(m, n).
Why prefixes? A recurrence needs smaller subproblems of the same shape. Dropping the last element of a prefix gives another prefix, so the full set of subproblems is just the (m + 1)(n + 1) index pairs (i, j). You could use suffixes instead, which means dropping the first element. The memoized code in a later chapter does exactly that. The reasoning is the same, mirrored.
What Optimal Substructure Means Here
A problem has optimal substructure when an optimal solution contains optimal solutions to subproblems. For LCS, the claim is concrete: if you take an LCS of X and Y and remove its last element, what remains is an LCS of a pair of shorter prefixes. The case analysis below tells you exactly which pair.
Let Z = z1 ... zk be any LCS of Xm and Yn. Look at the last elements xm and yn.
Case 1: The last elements match (`xm = yn`)
Claim. zk = xm = yn, and Z(k-1) is an LCS of X(m-1) and Y(n-1).
Why zk must be the matched element. Suppose zk ≠ xm. Then Z does not use the final xm/yn pair, so you could append xm to Z and get a common subsequence of length k + 1. That contradicts Z being longest. So Z ends with this symbol. You can also assume, without loss of generality, that zk is matched to positions m and n. If it were matched to earlier copies of the same symbol, you could move those matches to m and n without breaking the order.
Why the rest is optimal. Z(k-1) is a common subsequence of X(m-1) and Y(n-1). If some common subsequence W of those prefixes were longer than k - 1, then W followed by xm would be a common subsequence of X and Y with length greater than k. That is again a contradiction. This style of proof is called "cut and paste": you replace part of an optimal solution with something better and get an impossible result.
Case 2: The last elements differ and `zk ≠ xm`
Claim. Z is an LCS of X(m-1) and Y.
Since zk ≠ xm, no element of Z is matched to xm. So Z is a common subsequence of X(m-1) and Y. If some longer common subsequence of X(m-1) and Y existed, it would also be a common subsequence of X and Y, which contradicts the maximality of Z.
Case 3: The last elements differ and `zk ≠ yn`
This is the mirror of Case 2. Z is an LCS of X and Y(n-1).
When xm ≠ yn, zk cannot equal both of them, so at least one of Cases 2 and 3 applies. You do not know in advance which one, so you try both and keep the larger result.
The Recurrence
Turning the three cases into lengths gives:
| Condition | `c(i, j)` |
|---|---|
| `i = 0` or `j = 0` | `0` |
| `i, j > 0` and `xi = yj` | `c(i-1, j-1) + 1` |
| `i, j > 0` and `xi ≠ yj` | `max(c(i-1, j), c(i, j-1))` |
The base case covers an empty prefix: an empty sequence has only the empty subsequence in common with anything.
A Hand Expansion
Take X = "GAC" and Y = "AGC".
c(3, 3):C = C, so it is1 + c(2, 2).c(2, 2)compares"GA"with"AG". The last elementsAandGdiffer, so it ismax(c(1, 2), c(2, 1)).c(1, 2)compares"G"with"AG".G = G, so it is1 + c(0, 1) = 1.c(2, 1)compares"GA"with"A".A = A, so it is1 + c(1, 0) = 1.- So
c(2, 2) = 1andc(3, 3) = 2.
Both branches in step 2 reach 1, and they correspond to different answers. One gives "GC" and the other gives "AC". The recurrence fixes the length, but more than one sequence can achieve it. A later chapter handles these ties.
Checking the Recurrence Against Brute Force
A recurrence should be tested, not just argued for. The script below evaluates the recurrence by plain recursion, with no caching, and compares it with exhaustive search on many small random inputs.
from itertools import combinations
import random
def lcs_rec(a, b):
def c(i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return c(i - 1, j - 1) + 1
return max(c(i - 1, j), c(i, j - 1))
return c(len(a), len(b))
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
def lcs_brute(a, b):
for k in range(min(len(a), len(b)), 0, -1):
for idx in combinations(range(len(a)), k):
if is_subsequence("".join(a[i] for i in idx), b):
return k
return 0
random.seed(1)
for _ in range(300):
a = "".join(random.choices("ABC", k=random.randint(0, 7)))
b = "".join(random.choices("ABC", k=random.randint(0, 7)))
assert lcs_rec(a, b) == lcs_brute(a, b), (a, b)
print("recurrence agrees with brute force on 300 random pairs")
print(lcs_rec("GAC", "AGC")) # 2
print(lcs_rec("ABCBDAB", "BDCABA")) # 4a[i - 1] stands for xi, because the math indexes from 1 and Python indexes from 0. This shift causes most bugs in LCS code. Keep i and j as prefix lengths and subtract 1 only when you read a character.
The small alphabet "ABC" is chosen on purpose. It produces many repeated characters and ties, which are the inputs most likely to expose a wrong case.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Mismatch case uses `c(i-1, j-1)` only | Answer too small, e.g. `"AB"` vs `"B"` gives 0 | Take `max(c(i-1, j), c(i, j-1))` |
| Match case adds 1 to `max(c(i-1, j), c(i, j-1))` | Answer too large, can exceed `min(m, n)` | Add 1 to the diagonal `c(i-1, j-1)` |
| Mixing prefix lengths and 0-based indexes | Index errors or skipped first characters | Let `i`, `j` be lengths; read `a[i-1]`, `b[j-1]` |
| Resetting to 0 on mismatch | Computes longest common substring instead | Substrings need contiguity; subsequences do not |
| Missing base case for one empty prefix | Infinite recursion or negative indexes | Return 0 when `i == 0` or `j == 0` |
What the Recurrence Does Not Give You Yet
The plain recursive version is correct, but it is slow. Each mismatch makes two calls, and different call paths reach the same (i, j) many times. In the hand expansion, c(1, 1) could be reached through both branches if they were expanded further. The next chapter measures this repetition and shows why it makes dynamic programming worthwhile.
Exercise
Using the recurrence, compute c(4, 3) for X = "ABCB" and Y = "BCB". Show the first two levels of expansion.
Show answer
x4 = B and y3 = B match, so c(4, 3) = 1 + c(3, 2), comparing "ABC" with "BC". Those end in C and C, which match, so c(3, 2) = 1 + c(2, 1), comparing "AB" with "B". Those end in B and B, so c(2, 1) = 1 + c(1, 0) = 1. Total: c(4, 3) = 3, and the LCS is "BCB".
Exercise
A colleague writes the mismatch case as max(c(i-1, j), c(i, j-1), c(i-1, j-1)). Is the result still correct? Is anything lost?
Show answer
The result is still correct, because c(i-1, j-1) ≤ c(i-1, j) means the extra term never changes the maximum. It costs an extra lookup or recursive call per cell and suggests the author has not seen that the diagonal is dominated.
Exercise
Explain, using the cut-and-paste argument, why in Case 1 the prefix Z(k-1) must be an LCS of X(m-1) and Y(n-1) rather than just some common subsequence.
Show answer
Suppose a common subsequence W of X(m-1) and Y(n-1) were longer than k - 1. Appending the shared last element xm = yn to W gives a common subsequence of X and Y of length at least k + 1. That contradicts Z being an LCS of length k, so no such W exists and Z(k-1) is optimal.
Exercise
Rewrite the recurrence using suffixes: let s(i, j) be the LCS length of a[i:] and b[j:] with 0-based i and j. Give the base case and the two other cases.
Show answer
s(i, j) = 0 if i = len(a) or j = len(b). If a[i] = b[j], s(i, j) = 1 + s(i+1, j+1). Otherwise s(i, j) = max(s(i+1, j), s(i, j+1)). The answer is s(0, 0).