Problem Description
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. The allowed operations are:
- Insert a character
- Delete a character
- Replace a character
For example:
- Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: Replace 'h' with 'r' -> Delete 'r' -> Delete 'e'
- Input: word1 = "intention", word2 = "execution" Output: 5
Key Insights
- This is a classic dynamic programming problem.
- Use a 2D DP table where dp[i][j] represents the minimum edit distance between word1[0…i-1] and word2[0…j-1].
- Base cases: converting an empty string to a string of length j requires j insertions, and vice versa.
- Transition: If characters match then dp[i][j] = dp[i-1][j-1], otherwise take minimum among insertion, deletion, and replacement operations and add 1.
Space and Time Complexity
Time Complexity: O(mn), where m and n are the lengths of word1 and word2 respectively. Space Complexity: O(mn) due to the DP table used for storing computed distances.
Solution
We use a dynamic programming approach by constructing a 2D table dp of size (m+1) x (n+1), where m and n are the lengths of word1 and word2. Each dp[i][j] holds the minimum number of operations needed to convert the first i characters of word1 to the first j characters of word2. The algorithm includes the following steps:
- Initialize the base cases:
- dp[0][j] = j (converting an empty word1 to j characters of word2 requires j insertions)
- dp[i][0] = i (converting i characters of word1 to an empty word2 requires i deletions)
- Iterate over each character in word1 and word2:
- If the current characters are equal, no additional operation is needed and dp[i][j] = dp[i-1][j-1].
- Otherwise, choose the best operation among insertion (dp[i][j-1]), deletion (dp[i-1][j]), or substitution (dp[i-1][j-1]) and add 1.
- The answer is found in dp[m][n].
This method reliably computes the edit distance using a systematic DP approach, ensuring that all subproblems are solved and reused efficiently.