Strings DP
Two-string DP uses the state (i, j): the answer for the first i characters of one string and the first j of the other. If the current characters match, use the diagonal; otherwise take the best of dropping one character. LCS, edit distance, interleaving, wildcards and many more are this table with different rules.
How to recognise it
- Two strings compared character by character.
- Insertions, deletions or replacements to turn one string into another.
- Palindromes inside one string (compare it with its reverse, or use the state (i, j) of a substring).
The table
dp[i][j] for the first i characters of a and the first j of b
if a[i-1] == b[j-1]: use dp[i-1][j-1]
else: combine dp[i-1][j], dp[i][j-1] (and dp[i-1][j-1])
| Problem | Match | No match |
|---|---|---|
| LCS | diagonal + 1 | max(up, left) |
| longest common substring | diagonal + 1 | 0 (a block must be unbroken) |
| edit distance | diagonal | 1 + min(diagonal, up, left) |
| delete operations | via LCS: m + n - 2 × LCS | |
| distinct subsequences | ways(up) + ways(diagonal) | ways(up) |
| interleaving | the last character came from s1 or s2 |
One string
Palindromes use the state (i, j) for the substring s[i..j]: matching ends wrap the inside. The longest palindromic subsequence is also the LCS of s and its reverse.
Common mistakes
- Mixing up substring (contiguous) and subsequence (not).
- Off-by-one between string indexes and table indexes.
Problems
- Longest Common Subsequencemediumguide ready
- Longest common substringmediumguide ready
- Longest Palindromic Subsequencemediumguide ready
- Delete Operation for Two Stringsmediumguide ready
- Edit Distancemediumguide ready
- Find Longest Recurring Subsequence in Stringmediumguide ready
- Word Breakmediumguide ready
- Count All Palindromic Subsequence in a given Stringmediumguide ready
- LCS (Longest Common Subsequence) of three stringsmediumguide ready
- Interleaving Stringmediumguide ready
- Minimum Insertion Steps to Make a String Palindromehardguide ready
- Shortest Common Supersequence hardguide ready
- Distinct Subsequenceshardguide ready
- Wildcard Matchinghardguide ready