Given two strings word1 and word2, return the minimum number of operations needed to turn word1 into word2. Each operation is one of: insert a character, delete a character, or replace a character. (This is the Levenshtein distance.)
- 0 <= word1.length, word2.length <= 500
- Both strings are lowercase English letters
Give it a real try first. Even 15 minutes of struggle makes the solution stick far better.
Intuition
The brute force recursion tries all three operations at every mismatch, which is O(3^(m+n)). State: dp[i][j] = minimum operations to convert word1[0..i) into word2[0..j). Recurrence: if word1[i-1] == word2[j-1], then dp[i][j] = dp[i-1][j-1]. Otherwise take 1 plus the best of: delete from word1 (dp[i-1][j]), insert into word1 (dp[i][j-1]), or replace (dp[i-1][j-1]). Base cases: dp[i][0] = i (delete everything) and dp[0][j] = j (insert everything). Memoising the recursion gives m * n states; the table computes them row by row.
Algorithm
- Create a
(m + 1) x (n + 1)table; setdp[i][0] = ianddp[0][j] = j. - For each
ifrom 1 tomandjfrom 1 ton: - If the characters match, copy the diagonal
dp[i-1][j-1]. - Otherwise set
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). - Return
dp[m][n].
O(m * n)Space: O(m * n), reducible to O(n)class Solution: def minDistance(self, word1: str, word2: str) -> int: m, n = len(word1), len(word2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i # delete all for j in range(n + 1): dp[0][j] = j # insert all for i in range(1, m + 1): for j in range(1, n + 1): if word1[i - 1] == word2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j], # delete dp[i][j - 1], # insert dp[i - 1][j - 1]) # replace return dp[m][n]