Sub topic 8
Longest Common Subsequence
Working model
Assume you know Big-O notation, arrays, loops, strings, and how a two-dimensional table stores values. A subsequence is a sequence formed by deleting zero or more characters without changing the order of the remaining characters. The characters do not need to be adjacent.
The longest common subsequence (LCS) of two strings is their longest subsequence that appears in both strings. For example, BCBA is a common subsequence of ABCBDAB and BDCABA. The LCS length is 4.
Dynamic programming works here because the problem has:
- Optimal substructure: an optimal answer for larger prefixes uses optimal answers for smaller prefixes.
- Overlapping subproblems: the same prefix pairs occur repeatedly in a direct recursive solution.
Let dp[i][j] be the LCS length of the first i characters of a and the first j characters of b.
Recurrence and table order
The base cases are:
dp[0][j] = 0: an empty string has no common characters.dp[i][0] = 0: the same applies when the second prefix is empty.
For nonempty prefixes:
- If
a[i - 1] == b[j - 1], the matching characters extend an LCS:
dp[i][j] = dp[i - 1][j - 1] + 1
- Otherwise, discard one final character and keep the better result:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
Fill rows from top to bottom and cells from left to right. Each required neighbour is then already known.
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, so the time complexity is O(mn) and the space complexity is O(mn).
Common errors
The expression a[i - 1] matters because i counts characters while Python indexes from zero. Comparing a[i] would skip the first character and eventually access beyond the string.
A common subsequence is not necessarily a substring. A substring must be contiguous; an LCS may contain gaps.
If only the length is required, memory can be reduced to O(n) by keeping the previous and current rows. If the actual subsequence is required, retain the full table or use a separate reconstruction strategy.
Exercise
What is the LCS length of "AGGTAB" and "GXTXAYB", and what recurrence applies when the final characters match?
Show answer
The length is 4, for example "GTAB". When the final characters match, use dp[i][j] = dp[i - 1][j - 1] + 1.