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:
Insert a character- Delete a character- Replace a characterExample1:
Input: word1 = "horse", word2 = "ros"
Output:3Explanation:
horse -> rose (replace 'h' with 'r')
rose -> ros (remove 'e')
To solve the problem of finding the minimum number of operations required to convert word1 to word2, we can use Dynamic Programming (DP). This approach efficiently breaks down the problem into smaller subproblems and builds up the solution.
Understanding the Problem
Given two strings, word1 and word2, you can perform three operations on word1:
Insert a character.
Delete a character.
Replace a character.
The goal is to find the minimum number of these operations required to transform word1 into word2.
Example Walkthrough
Let's walk through Example 1 to understand the process:
Input:word1 = "horse", word2 = "ros"
Output:3
Explanation:
Replace 'h' with 'r': "horse" → "rorse"
Delete 'r': "rorse" → "rose"
Delete 'e': "rose" → "ros"
Total operations = 3.
Dynamic Programming Approach
To efficiently solve this problem, we can use a DP table where:
Rows represent characters of word1 (including an empty string).
Columns represent characters of word2 (including an empty string).
Each cell dp[i][j] will represent the minimum number of operations required to convert the first i characters of word1 to the first j characters of word2.
dp[i][0] = i (converting first i characters of word1 to empty string requires i deletions).
dp[0][j] = j (converting empty string to first j characters of word2 requires j insertions).
Fill the Table:
Iterate through each character of word1 (index i) and word2 (index j).
If word1[i-1] == word2[j-1], no operation is needed, so dp[i][j] = dp[i-1][j-1].
If they are not equal, consider the minimum of the three possible operations:
Insert:dp[i][j-1] + 1
Delete:dp[i-1][j] + 1
Replace:dp[i-1][j-1] + 1
Set dp[i][j] to the minimum of these values.
Result:
The value in dp[m][n] will be the minimum number of operations required to convert word1 to word2, where m and n are the lengths of word1 and word2, respectively.
Visualization
Let's visualize the DP table for Example 1:
code
word1: "" h o r s e
word2: "" r o s
Initialize the table:
"" r o s
"" 0 1 2 3
h 1
o 2
r 3
s 4
e 5
Fill the table step-by-step based on the rules.
Python Implementation
Here's how you can implement the above approach in Python:
python
def minDistance(word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
# Create a (m+1) x (n+1) DP table
dp = [[0]*(n+1) for _ in range(m+1)]
# Initialize the first row and first column
for i in range(m+1):
dp[i][0] = i # Deleting all characters from word1
for j in range(n+1):
dp[0][j] = j # Inserting all characters to word1 to make word2
# Fill the DP table
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] == word2[j-1]:
# Characters match, no operation needed
dp[i][j] = dp[i-1][j-1]
else:
# Characters don't match, consider all three operations
insert = dp[i][j-1] + 1 # Insert
delete = dp[i-1][j] + 1 # Delete
replace = dp[i-1][j-1] + 1 # Replace
dp[i][j] = min(insert, delete, replace)
return dp[m][n]
# Test Cases
if __name__ == "__main__":
word1 = "horse"
word2 = "ros"
print(f"Minimum operations to convert '{word1}' to '{word2}': {minDistance(word1, word2)}") # Output: 3
word1 = "intention"
word2 = "execution"
print(f"Minimum operations to convert '{word1}' to '{word2}': {minDistance(word1, word2)}") # Output: 5
Explanation of the Code
Initialization:
We create a DP table dp with dimensions (m+1) x (n+1), where m and n are the lengths of word1 and word2, respectively.
The first row and first column are initialized based on the number of insertions and deletions required.
Filling the DP Table:
We iterate through each character of word1 and word2.
If the current characters match, we inherit the value from the diagonal cell (dp[i-1][j-1]).
If they don't match, we consider the minimum operations among insert, delete, and replace.
Result:
The value at dp[m][n] gives the minimum number of operations needed.
Time and Space Complexity
Time Complexity: O(m * n), where m and n are the lengths of word1 and word2. This is because we fill a table of size m * n, and each cell takes constant time to compute.
Space Complexity: O(m * n), due to the storage of the DP table.
Optimization (Space)
If space optimization is required (especially for large strings), you can reduce the space complexity to O(min(m, n)) by using two one-dimensional arrays instead of a two-dimensional table. However, the above implementation is straightforward and efficient for most practical purposes.
Conclusion
The Dynamic Programming approach efficiently solves the problem by breaking it down into smaller subproblems and building up the solution. The key idea is to consider the minimum operations required at each step and use previously computed results to find the optimal solution.