Sub topic 11
Longest common subsequence
This chapter assumes you know Big-O notation, basic recursion, and 2D arrays. It builds on the idea of optimal substructure and on tabulation from the previous chapters.
The problem
A subsequence of a string keeps the original order of characters but may skip some. For ABCBDAB, the strings BCDB and ACA are subsequences. A substring must be contiguous, so BCDB is not a substring.
The longest common subsequence (LCS) of two strings a and b is the longest string that is a subsequence of both. For ABCBDAB and BDCABA, the LCS length is 4. One answer is BCBA. Others also have length 4, such as BDAB, so the LCS string is not unique, but its length is.
LCS is the basis of diff tools and sequence comparison. In GATE questions you are usually asked for the length, the table contents, or the running time.
Optimal substructure
Let a have length m and b have length n. Define L(i, j) as the LCS length of the first i characters of a and the first j characters of b. Look at the last characters, a[i] and b[j]:
- If they are equal, some LCS ends with that character. Remove it from both strings and solve the smaller problem. So
L(i, j) = L(i-1, j-1) + 1. - If they differ, at most one of them can end the LCS. Drop the last character of either string and keep the better result. So
L(i, j) = max(L(i-1, j), L(i, j-1)).
The base cases are L(i, 0) = 0 and L(0, j) = 0, because an empty string has no common characters with anything.
The subproblems overlap. Both L(i-1, j) and L(i, j-1) need L(i-1, j-1). A plain recursion without caching can take exponential time, about 2^(m+n) calls in the worst case. There are only (m+1)(n+1) distinct subproblems, so caching removes the blow-up.
Table-filling order
Cell (i, j) depends on its left, upper, and upper-left neighbours. Filling the table row by row, left to right, guarantees those cells are ready.
def lcs_length(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])
return dp[m][n]
print(lcs_length('ABCBDAB', 'BDCABA')) # 4The table has (m+1)(n+1) cells and each takes constant work, so time is O(mn) and space is O(mn).
Tracing by hand
Take a = "ABC" and b = "AC". Rows are prefixes of a, and columns are prefixes of b.
| Row | empty | A | C |
|---|---|---|---|
| empty | 0 | 0 | 0 |
| A | 0 | 1 | 1 |
| AB | 0 | 1 | 1 |
| ABC | 0 | 1 | 2 |
Check a few cells. (A, A) matches, so it is 0 + 1 = 1. (A, C) does not match, so it is max(0, 1) = 1. (ABC, C) matches, so it is the upper-left value plus one, 1 + 1 = 2. The answer is the bottom-right cell, 2, for the subsequence AC.
Recovering the sequence itself
The table gives only the length. To rebuild one LCS, start at (m, n) and walk back:
- If
a[i-1] == b[j-1], record the character and move to(i-1, j-1). - Otherwise move to the neighbour with the larger value: up if
dp[i-1][j] >= dp[i][j-1], else left. - Stop when
iorjreaches 0, then reverse the recorded characters.
def lcs_string(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))
print(lcs_string('ABCBDAB', 'BDCABA')) # BCBAThe walk takes O(m + n) time, but it needs the full table. That has a cost, covered next.
Space reduction and its limit
Each row depends only on the previous row. Keeping two rows lowers space to O(min(m, n)) if you make the shorter string the column index. This is enough for the length. It is not enough for the walk-back, because the walk needs earlier rows. Recovering the string in linear space needs Hirschberg's divide-and-conquer method, which is beyond GATE.
Memoized version
Top-down code follows the recurrence directly and computes only the cells it reaches.
from functools import lru_cache
def lcs_memo(a, b):
@lru_cache(maxsize=None)
def L(i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return L(i - 1, j - 1) + 1
return max(L(i - 1, j), L(i, j - 1))
return L(len(a), len(b))
print(lcs_memo('ABCBDAB', 'BDCABA')) # 4It has the same O(mn) bound. Python's recursion limit (1000 by default) makes it fail on long strings, which is one practical reason to prefer tabulation.
Common errors
- Confusing subsequence with substring. A substring version needs
dp[i][j] = 0on a mismatch, and the answer is the maximum over all cells. - Forgetting the extra zero row and column, which shifts every index by one.
- Using
a[i]instead ofa[i-1]in code when the table is one larger than the strings. - Adding 1 on a mismatch. Only a match increases the value.
- Reporting
dp[m][n]as the string rather than its length.
Link to edit distance
LCS is closely related to edit distance with only insertions and deletions. That distance is m + n - 2 * LCS. The next chapter extends the same table idea by adding substitutions.
Exercise
Compute the LCS length of "AGGTAB" and "GXTXAYB", and state the time and space of the standard table method for strings of lengths m and n.
Show answer
The LCS is "GTAB", so the length is 4. The standard table method takes O(mn) time and O(mn) space. With only two rows kept, the space drops to O(min(m, n)) but you can no longer rebuild the string directly.
Exercise
How many insertions and deletions turn "ABCBDAB" into "BDCABA" at minimum?
Show answer
The LCS length is 4, so the cost is 7 + 6 - 2 * 4 = 5.