Edit Distance

Pattern: Strings DP

medium

dp[i][j] is the fewest operations turning the first i characters of word1 into the first j of word2. Equal last characters cost nothing; otherwise take 1 + the best of replace (diagonal), delete (above) and insert (left).

The problem

Return the fewest insertions, deletions and replacements of single characters that turn word1 into word2.

Think first

  • What can happen to word1's last character?
  • Which smaller problem does each operation leave?
  • What is dp[i][0]?

Hints

    Brute force, and why it fails

    Try every operation sequence: exponential.

    The key insight

    Each operation shortens one or both prefixes by one, so three neighbours cover every option.

    Dry run

    ops1

    'horse' to 'ros'. Replace h with r: rorse.

    Step 1 of 3

    The plan

    dp[i][0] = i; dp[0][j] = j
    dp[i][j] = dp[i-1][j-1] if equal else 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    Two rows.

    Edge cases

    • One empty word: the other's length.
    • Equal words: 0.
    • One character each.
    I've built my logic, show the code

    Java

    class Solution {
        public int minDistance(String word1, String word2) {
            int m = word1.length(), n = word2.length();
            int[][] dp = new int[m + 1][n + 1];     // dp[i][j]: operations to turn the first i characters into the first j
            for (int i = 0; i <= m; i++) dp[i][0] = i;   // delete everything
            for (int j = 0; j <= n; j++) dp[0][j] = j;   // insert everything
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = word1.charAt(i - 1) == word2.charAt(j - 1)
                        ? dp[i - 1][j - 1]                                                   // nothing to do
                        : 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));   // replace, delete, insert
            return dp[m][n];
        }
    }

    C++

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            int m = static_cast<int>(word1.size()), n = static_cast<int>(word2.size());
            vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));   // operations to turn the first i characters into the first j
            for (int i = 0; i <= m; i++) dp[i][0] = i;   // delete everything
            for (int j = 0; j <= n; j++) dp[0][j] = j;   // insert everything
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = word1[i - 1] == word2[j - 1]
                        ? dp[i - 1][j - 1]                                           // nothing to do
                        : 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1]));   // replace, delete, insert
            return dp[m][n];
        }
    };

    Python

    class Solution:
        def minDistance(self, word1: str, word2: str) -> int:
            prev = list(range(len(word2) + 1))      # turning "" into prefixes of word2: insert everything
            for i, a in enumerate(word1, 1):
                cur = [i]                           # turning i characters into "": delete everything
                for j, b in enumerate(word2, 1):
                    cur.append(prev[j - 1] if a == b else 1 + min(prev[j - 1], prev[j], cur[j - 1]))   # replace, delete, insert
                prev = cur
            return prev[-1]

    Common mistakes

    • Forgetting the base row and column.
    • Charging for matching characters.

    Similar problems