Introduction#
String DP usually falls into two families:
- prefix DP over one or two strings
- interval DP over one substring
The state definition must say whether we are matching prefixes, deleting characters, editing source into target, or repairing an interval.
Two-Prefix DP#
For LCS:
dp[i][j] = LCS length between text1[:i] and text2[:j]
If the current characters match:
dp[i][j] = dp[i - 1][j - 1] + 1
If they do not match:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
Edit Distance#
For edit distance, the direction matters:
dp[i][j] = minimum operations to convert word1[:i] into word2[:j]
On mismatch, the three operations are:
- delete from source
- insert target character
- replace source character
Delete-Only DP#
For delete-only problems, replacement and insertion are not legal. On mismatch, choose which side to delete:
1 + min(delete from word1, delete from word2)
Weighted delete problems use character cost instead of unit cost.
Interval Palindrome DP#
For palindrome subsequence or insertion problems:
dp[left][right] = answer for s[left:right+1]
Fill shorter intervals first. If the ends match, use the inner interval. If they do not, drop or repair one side depending on the problem.
Common Mistakes#
- Mixing substring and subsequence.
- Forgetting that
dp[i][j]uses prefix lengths, while characters usei - 1andj - 1. - Mixing insert/delete direction in edit distance.
- Adding a replace branch to delete-only problems.
- Filling interval DP in the wrong order.
Related LeetCode#
LC 72Edit DistanceLC 97Interleaving StringLC 115Distinct SubsequencesLC 139Word BreakLC 516Longest Palindromic SubsequenceLC 583Delete Operation for Two StringsLC 712Minimum ASCII Delete Sum for Two StringsLC 1092Shortest Common SupersequenceLC 1143Longest Common SubsequenceLC 1312Minimum Insertion Steps to Make a String Palindrome
