Sub topic 4
Optimal Substructure and the LCS Recurrence
This chapter assumes you know recursion with base cases, the definition of a subsequence, and the LCS problem statement from earlier chapters. The goal is to derive a recurrence: a formula that defines the LCS length of two strings in terms of the LCS lengths of shorter strings.
Prefixes as Subproblems
Let a have length m and b have length n. Write L(i, j) for the LCS length of the prefix a[:i] (the first i characters) and the prefix b[:j]. The answer to the full problem is L(m, n).
A problem has optimal substructure when an optimal solution contains optimal solutions to smaller subproblems. To show that LCS has this property, look at the last characters of the two prefixes, a[i-1] and b[j-1].
The Three Cases
Let Z be any LCS of a[:i] and b[:j], with length k.
- The last characters match (
a[i-1] == b[j-1]). ThenZmust end with that character. If it did not, appending the character toZwould give a longer common subsequence. Removing that final character leaves an LCS ofa[:i-1]andb[:j-1]. - The last characters differ, and
Zdoes not end witha[i-1]. ThenZis a common subsequence ofa[:i-1]andb[:j], and it must be a longest one. - The last characters differ, and
Zdoes not end withb[j-1]. ThenZis an LCS ofa[:i]andb[:j-1].
When the last characters differ, Z cannot end with both of them, so case 2 or case 3 always applies. Each case uses a cut-and-paste argument: if the smaller piece were not optimal, you could swap in a better one and get a longer LCS overall, which is a contradiction.
The Recurrence
| Condition | L(i, j) |
|---|---|
| i = 0 or j = 0 | 0 |
| a[i-1] == b[j-1] | L(i-1, j-1) + 1 |
| otherwise | max(L(i-1, j), L(i, j-1)) |
The following code checks the recurrence against brute-force enumeration on small inputs. Both run in exponential time, so use them only on short strings.
from itertools import combinations
def L(a, b, i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return L(a, b, i - 1, j - 1) + 1
return max(L(a, b, i - 1, j), L(a, b, i, j - 1))
def brute(a, b):
for k in range(min(len(a), len(b)), -1, -1):
subs_b = {"".join(c) for c in combinations(b, k)}
if any("".join(c) in subs_b for c in combinations(a, k)):
return k
for a, b in [("ABCBDAB", "BDCABA"), ("AGGTAB", "GXTXAYB"), ("ABC", "XYZ")]:
print(a, b, L(a, b, len(a), len(b)), brute(a, b)) # 4 4, 4 4, 0 0Common Errors
- Off-by-one indexing.
L(i, j)refers to prefix lengths, so the last characters area[i-1]andb[j-1], nota[i]andb[j]. - Greedy skipping on a mismatch. Dropping a character from only one string can lose the optimum. You need the max of both options.
- Extra work on a match. Taking
max(L(i-1, j-1) + 1, L(i-1, j), L(i, j-1))is still correct but unnecessary. Case 1 proves that the diagonal is always optimal when the last characters match.
Exercise
Use the recurrence to compute L for a = "AB" and b = "BA", and name every LCS of those two strings.
Show answer
The last characters B and A differ, so L(2,2) = max(L(1,2), L(2,1)). For L(1,2), "A" vs "BA" ends in a match, giving 1 + L(0,1) = 1. For L(2,1), "AB" vs "B" also ends in a match, giving 1. So L(2,2) = 1, and both "A" and "B" are longest common subsequences.
Exercise
Why can't case 2 and case 3 both fail when a[i-1] != b[j-1]?
Show answer
If both failed, Z would end with a[i-1] and also with b[j-1]. A sequence has only one last character, so the two characters would be equal, which contradicts the assumption that they differ.