SDE & MLE Prep

72. Edit Distance

Problem

Return the minimum number of single-character operations (insert, delete or replace) needed to turn word1 into word2.

Example: word1 = "horse", word2 = "ros" → 3; "intention" → "execution" takes 5

Constraints: lengths ≤ 500.

dp[i][j] = edits to turn a[:i] into b[:j]. Match → dp[i−1][j−1]; else 1 + min(replace dp[i−1][j−1], delete dp[i−1][j], insert dp[i][j−1]). Base: dp[i][0] = i, dp[0][j] = j.

         ""  r  o  s
     ""   0  1  2  3
     h    1  1  2  3
     o    2  2  1  2
     r    3  2  2  2
     s    4  3  3  2
     e    5  4  4  3   <- horse -> ros = 3

Complexity: O(m·n).

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        n = len(word2)
        dp = list(range(n + 1))
        for i, a in enumerate(word1, 1):
            diag, dp[0] = dp[0], i
            for j in range(1, n + 1):
                up = dp[j]
                dp[j] = diag if a == word2[j - 1] else 1 + min(diag, up, dp[j - 1])
                diag = up
        return dp[n]