Delete Operation for Two Strings
Pattern: Strings DP
Deleting characters from both words until they are equal leaves a common subsequence; keep the longest one. The answer is m + n - 2 × LCS.
The problem
Return the fewest single-character deletions (from either word) needed to make word1 and word2 equal.
Think first
- What is left after the deletions?
- Which common subsequence should be kept?
- How many characters are deleted?
Hints
Brute force, and why it fails
Try every set of deletions: exponential.
The key insight
Keeping the LCS minimises deletions, so this is one LCS computation.
Dry run
| lcs | 2 |
|---|
'sea' and 'eat': the LCS is 'ea' (length 2).
Step 1 of 2
The plan
return m + n - 2 × LCS(word1, word2)
Complexity
- Time
O(m × n)- Space
O(n)
One LCS table.
Edge cases
- Equal words: 0.
- No common letters: m + n.
- One empty word.
I've built my logic, show the code
Java
class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.length();
int[][] dp = new int[m + 1][n + 1]; // the LCS table
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = word1.charAt(i - 1) == word2.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
return m + n - 2 * dp[m][n]; // delete everything outside the longest common subsequence
}
}C++
class Solution {
public:
int minDistance(string word1, string word2) {
int m = static_cast<int>(word1.size()), n = static_cast<int>(word2.size());
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); // the LCS table
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = word1[i - 1] == word2[j - 1] ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]);
return m + n - 2 * dp[m][n]; // delete everything outside the longest common subsequence
}
};Python
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
prev = [0] * (len(word2) + 1) # the LCS table, one row at a time
for a in word1:
cur = [0]
for j, b in enumerate(word2, 1):
cur.append(prev[j - 1] + 1 if a == b else max(prev[j], cur[j - 1]))
prev = cur
return len(word1) + len(word2) - 2 * prev[-1] # delete everything outside the LCSCommon mistakes
- Counting replacements, which are not allowed here.
- Subtracting the LCS once.