Video in progress

Strong Middle 🧠 Problem solving

How do you compute the minimum number of edits (edit distance) to turn one word into another?

2D DP: dp[i][j] is the cost of making the first i letters of one word match the first j letters of the other. If the letters are equal, take the diagonal value; otherwise take the cheapest of insert, delete and replace, plus one. O(n·m) time.

📖 Answer

"kitten" → "sitting" = 3 (k→s, e→i, a g added at the end).

static int editDistance(String a, String b) {
    int n = a.length(), m = b.length();
    int[] prev = new int[m + 1], cur = new int[m + 1];
    for (int j = 0; j <= m; j++) prev[j] = j;      // j insertions from the empty string
    for (int i = 1; i <= n; i++) {
        cur[0] = i;                                // i deletions
        for (int j = 1; j <= m; j++) {
            if (a.charAt(i - 1) == b.charAt(j - 1)) {
                cur[j] = prev[j - 1];
            } else {
                cur[j] = 1 + Math.min(prev[j - 1],              // replace
                             Math.min(prev[j], cur[j - 1]));    // delete, insert
            }
        }
        int[] t = prev; prev = cur; cur = t;
    }
    return prev[m];
}

Instead of a full dp[n+1][m+1] table, two rows are used: each row looks only at the previous one. Memory is O(m). For two 10,000-character texts, that's the difference between 400 MB and 80 KB.

But you lose something: only the number is left, and you can't reconstruct the sequence of edits. If you need to show a diff, you need the full table (or a smarter method like Hirschberg).

In practice: "Did you mean...?" in search, and fuzzy matching of last names (Saidov/Saydov). On a large dictionary, computing O(n·m) against every word is expensive; there you narrow the candidates beforehand with a BK-tree or n-gram indexes.