Dynamic Programming · Pattern 8 of 12
String DP: two indexes, one per string
dp[i][j] describes the first i characters of one string and the first j of the other (or the substring s[i..j]). If the last characters match, move both; if not, try each way of dropping one.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Compare two strings: common subsequence, edits, interleaving
- Palindromic subsequences or substrings
- Match a string against a pattern with
.,*or?
The template
// LCS: dp[i][j] = longest common subsequence of a[0..i) and b[0..j)
int longestCommonSubsequence(String a, String b) {
int n = a.length(), m = b.length();
int[][] dp = new int[n + 1][m + 1]; // row 0 and column 0: an empty string, LCS 0
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[n][m];
}
// Edit Distance: dp[i][j] = edits to turn a[0..i) into b[0..j)
int minDistance(String a, String b) {
int n = a.length(), m = b.length();
int[][] dp = new int[n + 1][m + 1];
for (int i = 0; i <= n; i++) dp[i][0] = i; // delete everything
for (int j = 0; j <= m; j++) dp[0][j] = j; // insert everything
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); // replace, delete, insert
return dp[n][m];
}
// Longest Palindromic Subsequence: dp[i][j] = answer for s[i..j]
int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int i = n - 1; i >= 0; i--) { // i goes down, so row i + 1 is ready
dp[i][i] = 1;
for (int j = i + 1; j < n; j++)
dp[i][j] = s.charAt(i) == s.charAt(j)
? dp[i + 1][j - 1] + 2
: Math.max(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
} def longest_common_subsequence(a, b):
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)] # row 0 / column 0: an empty string
for i in range(1, n + 1):
for j in range(1, m + 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[n][m]
def min_distance(a, b):
n, m = len(a), len(b)
dp = [[i + j if i == 0 or j == 0 else 0 for j in range(m + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else: # replace, delete, insert
dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
return dp[n][m]
def longest_palindrome_subseq(s):
n = len(s)
dp = [[0] * n for _ in range(n)] # dp[i][j] = answer for s[i..j]
for i in range(n - 1, -1, -1): # i goes down, so row i + 1 is ready
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1] // LCS: dp[i][j] = longest common subsequence of a[0..i) and b[0..j)
int longestCommonSubsequence(string a, string b) {
int n = a.size(), m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = a[i - 1] == b[j - 1] ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]);
return dp[n][m];
}
// Edit Distance: dp[i][j] = edits to turn a[0..i) into b[0..j)
int minDistance(string a, string b) {
int n = a.size(), m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 0; i <= n; i++) dp[i][0] = i; // delete everything
for (int j = 0; j <= m; j++) dp[0][j] = j; // insert everything
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dp[i][j] = a[i - 1] == b[j - 1]
? dp[i - 1][j - 1]
: 1 + min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}); // replace, delete, insert
return dp[n][m];
}
// Longest Palindromic Subsequence: dp[i][j] = answer for s[i..j]
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = n - 1; i >= 0; i--) { // i goes down, so row i + 1 is ready
dp[i][i] = 1;
for (int j = i + 1; j < n; j++)
dp[i][j] = s[i] == s[j] ? dp[i + 1][j - 1] + 2 : max(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
} const table = (r, c) => Array.from({ length: r }, () => new Array(c).fill(0));
// LCS: dp[i][j] = longest common subsequence of a[0..i) and b[0..j)
function longestCommonSubsequence(a, b) {
const n = a.length, m = b.length, dp = table(n + 1, m + 1);
for (let i = 1; i <= n; i++)
for (let j = 1; j <= m; j++)
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[n][m];
}
// Edit Distance: dp[i][j] = edits to turn a[0..i) into b[0..j)
function minDistance(a, b) {
const n = a.length, m = b.length, dp = table(n + 1, m + 1);
for (let i = 0; i <= n; i++) dp[i][0] = i; // delete everything
for (let j = 0; j <= m; j++) dp[0][j] = j; // insert everything
for (let i = 1; i <= n; i++)
for (let j = 1; j <= m; j++)
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]); // replace, delete, insert
return dp[n][m];
}
// Longest Palindromic Subsequence: dp[i][j] = answer for s[i..j]
function longestPalindromeSubseq(s) {
const n = s.length, dp = table(n, n);
for (let i = n - 1; i >= 0; i--) { // i goes down, so row i + 1 is ready
dp[i][i] = 1;
for (let j = i + 1; j < n; j++)
dp[i][j] = s[i] === s[j] ? dp[i + 1][j - 1] + 2 : Math.max(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
} The variations
-
1Two strings, a prefix of each
If the last characters match, use
dp[i - 1][j - 1]. Otherwise drop a character from one string or the other (LCS), or pay for an edit (Edit Distance). Counting versions add instead: Distinct Subsequences, Interleaving String and Ways to Form a Target all have this shape.Now you solve -
2Contiguous match: common substring
dp[i][j]= length of the common run ending ata[i - 1]andb[j - 1]. A match extends the diagonal by 1; a mismatch resets to 0. The answer is the biggest cell, not the last one.Now you solve -
3Palindromes inside one string
dp[i][j]works ons[i..j]. Equal ends add 2 to the inside; otherwise drop one end. Minimum insertions = n minus the longest palindromic subsequence. For substrings,isPal[i][j] = s[i] == s[j] && isPal[i + 1][j - 1], which also feeds Palindrome Partitioning II. -
4Pattern matching with wildcards
dp[i][j]= doess[0..i)matchp[0..j). A*either matches nothing (usedp[i][j - 2]for regex,dp[i][j - 1]for wildcard) or eats one more character ofs(usedp[i - 1][j]).Now you solve -
5One string, answer ending at i
Longest Valid Parentheses:
dp[i]= the longest valid run ending ati, built from the run just before its matching(. Ways to Separate Numbers usesdp[i][len]with the last number's length as part of the state.Now you solve
Mistakes to avoid
- Mixing up subsequence and substring: for a substring, a mismatch resets
dp[i][j]to 0 and the answer is the max over all cells. - Forgetting the empty-string row and column: Edit Distance needs
dp[i][0] = ianddp[0][j] = j. - Filling a palindrome table
dp[i][j]withigoing up: it readsdp[i + 1][...], soimust go down (or fill by length).
Mark it done once you can write the template from memory and you have solved the worked examples yourself.