Algo-Sim › Dynamic Programming

Edit Distance

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Find the minimum number of single-character inserts, deletes and replacements to turn word1 into word2.

Problem

Given word1 and word2, return the fewest single-character operations that turn word1 into word2. An operation inserts a character, deletes one, or replaces one with another.

Constraints

Edge cases to test

Follow-up questions

How do you just check distance ≤ 1?
Two pointers: skip one mismatch and compare the rest (One Edit Distance, LC 161): O(n).
How do you speed up a small k bound?
Only fill cells within k of the diagonal: O(k·n) (Ukkonen’s banded DP).

Solution

Java

public int minDistance(String word1, String word2) {
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 0; i <= m; i++) dp[i][0] = i;
    for (int j = 0; j <= n; j++) dp[0][j] = j;
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                dp[i][j] = 1 + Math.min(dp[i - 1][j - 1],
                        Math.min(dp[i - 1][j], dp[i][j - 1]));
            }
        }
    }
    return dp[m][n];
}

Python

def min_distance(word1, word2):
    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
    for j in range(n + 1):
        dp[0][j] = j
    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 - 1],
                                   dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minDistance(string &word1, string &word2) {
        int m = int(word1.size()), n = int(word2.size());
        vector<vector<int>> dp = vector<vector<int>>(m + 1, vector<int>(n + 1));
        for (int i = 0; i <= m; i++)
            dp[i][0] = i;
        for (int j = 0; j <= n; j++)
            dp[0][j] = j;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1[i - 1] == word2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + std::min(dp[i - 1][j - 1],
                                            std::min(dp[i - 1][j], dp[i][j - 1]));
                }
            }
        }
        return dp[m][n];
    }
};

More Dynamic Programming problems