String DP: LCS, edit distance, palindromic subsequence
Two-string DP puts one string on each axis of a table. Longest common subsequence and edit distance fill it cell by cell, moving diagonally on matches.
Before you start: Grid DP: paths, minimum path sum, obstacles.
Longest common subsequence
The idea
Two strings share a subsequence when its characters appear in both, in order, with gaps allowed. ACBD and ABD share A, B, D.
Comparing every subsequence of one string with every subsequence of the other takes 2ⁿ × 2ᵐ checks. A table avoids almost all of them.
Intuition
Take ACD and AD. Cell (i, j) asks: how long is the best common subsequence of the first i and the first j characters?
When the two last characters match, they extend the answer for both shorter prefixes. Take the diagonal cell and add 1.
D matches D, so any best answer for AC and A can be followed by D. Nothing better exists, because using D once uses it in both strings.
When they differ, one of the two last characters is unused. Take the larger of the cell above and the cell to the left.
Complexity
The table has m · n cells and each costs O(1), so the time is O(m · n). Checking every subsequence grows as 2ⁿ.
The y axis is logarithmic. For two strings of 14 characters the table has 196 cells, but there are 16,384 subsequences of one string alone.
Each row reads only the row above and the cell to its left. Two rows of length n + 1 give O(n) space when only the length is needed.
Pitfalls
The table has one extra row and column for the empty prefix. Row i compares a[i − 1], so the strings are indexed one lower than the table.
A subsequence may skip characters. C is skipped here, and A, B, D still count as shared.
Variations
The longest palindromic subsequence of s is the LCS of s and its reverse. Deleting to make two strings equal costs m + n − 2 · LCS.
Edit distance fills the same table, but counts edits instead of matches. The next lesson builds it.
Edit distance
The idea
How few edits turn KIT into KN? An edit inserts, deletes or replaces one character, and here 2 are enough.
Spell checkers rank suggestions by edit distance. Searching every sequence of edits is far too slow, so we fill a table.
Intuition
Take the shorter KI and KN first. Row 0 and column 0 count up: one delete or one insert per character.
A cell has three ways in: replace (diagonal), delete (above), insert (left). Take the cheapest and add 1.
Replace keeps both prefixes one character shorter. Delete drops a character of the first word. Insert adds a character of the second.
When the two last characters match, nothing needs editing. Copy the diagonal cell.
Complexity
The table has m · n cells, each filled from three neighbours: O(m · n). Trying every edit sequence grows exponentially.
Each row reads only the row above and the cell to its left. Two rows give O(min(m, n)) space for the distance alone.
Pitfalls
Leaving the borders at 0 says KN can be built from nothing for free. Fill row 0 with 0, 1, 2 … and column 0 the same way.
A replace costs 1 only when the characters differ. When they match, adding 1 to the diagonal gives a wrong, larger answer.
Variations
Longest palindromic subsequence fills only the upper triangle. Cell (i, j) covers s[i..j] and reads the cells below and to its left.
Distinct subsequences counts instead of maximising. A match adds the diagonal and the cell above; a mismatch copies the cell above.
Code
Pseudocode
lcs(a, b):
m ← length of a, n ← length of b
dp ← (m + 1) × (n + 1) table of zeros
for i ← 1 to m
for j ← 1 to n
if a[i] = b[j]: 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]
Python
def lcs(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]
JavaScript
function lcs(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
Java
static int lcs(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
Practice problems (7)
Where does a match come from? Warm-up
The LCS table is being filled and the two last characters of the current prefixes are equal. Pick the rule that computes the cell.
Fill the LCS table Warm-up
Follow the longest-common-subsequence table for BAD and ABD. Answer each question before the step plays.
Longest common subsequence Standard
Return the length of the longest common subsequence of text1 and text2. A subsequence keeps the original order but may skip characters. Return 0 when the strings share none.
Edit distance Standard
Return the fewest operations that turn word1 into word2. One operation inserts a character, deletes a character, or replaces a character.
Longest palindromic subsequence Standard
Return the length of the longest palindromic subsequence of s. A subsequence keeps the original order but may skip characters.
Delete operations for two strings Standard
Return the fewest characters you must delete, from either word, to make word1 and word2 equal.
Distinct subsequences Challenge
Count how many distinct subsequences of s equal t. Two subsequences are different when they use different index sets, even if they spell the same string.
Related topics
Next on the path: Space optimization: rolling rows and variables