Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
Before we proceed, let’s clear out any ambiguities:
To solve the problem, we can use Dynamic Programming (DP). We need to maintain a DP table where dp[i][j]
represents the minimum edit distance between the first i
characters of word1
and the first j
characters of word2
.
We can break down the problem into the following steps:
Here is the C++ implementation of the solution:
#include <vector>
#include <string>
#include <algorithm>
class Solution {
public:
int minDistance(std::string word1, std::string word2) {
int m = word1.size();
int n = word2.size();
// DP table with (m+1)x(n+1)
std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1, 0));
// Initialize for the case when one of the strings is empty
for(int i = 1; i <= m; i++) {
dp[i][0] = i; // Deleting all characters in word1
}
for(int j = 1; j <= n; j++) {
dp[0][j] = j; // Inserting all characters to form word2
}
// Fill the DP table
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(word1[i-1] == word2[j-1]) {
dp[i][j] = dp[i-1][j-1]; // No change needed
} else {
dp[i][j] = std::min({dp[i-1][j] + 1, // Delete
dp[i][j-1] + 1, // Insert
dp[i-1][j-1] + 1}); // Replace
}
}
}
return dp[m][n];
}
};
The time complexity of this solution is (O(m \times n)), where (m) is the length of word1
and (n) is the length of word2
. This is because we need to fill an (m \times n) DP table.
The space complexity is also (O(m \times n)), which is the space required to store the DP table.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?