SDE & MLE Prep

583. Delete Operation for Two Strings

Problem

Return the minimum number of characters you must delete in total from word1 and word2 to make them equal.

Example: word1 = "sea", word2 = "eat" → 2

Characters kept = the LCS; everything else is deleted: m + n − 2·LCS.

Complexity: O(m·n).

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