Lesson 8 · Dynamic programming

Edit Distance

The fewest single-character edits that turn one string into another. Each cell of the table asks one question: what was the last edit?

Edit Distance concept diagramThe edit distance table for kitten against sitting. The optimal path runs down the diagonal and ends with one step right; its three edits are substitute k to s, substitute e to i, and insert g, so the bottom-right cell is 3. Beside it, a cell takes the minimum of its diagonal neighbour for substitute, the cell above for delete, and the cell to the left for insert.·sitting·kitten01234567112345672212345633212345443212345543223466543323one cell, three neighboursdp[i−1][j−1]dp[i−1][j]dp[i][j−1]dp[i][j]diagonal: substitute +1, match +0from above: delete from A +1from the left: insert from B +1orange = an edit on the best path: k→s, e→i, insert g · blue = free match · answer 3
1

Three Operations, One Number

The edit distance between two strings, also called the Levenshtein distance, is the smallest number of single-character edits that turns one into the other. Three edits are allowed and each costs 1: insert a character, delete a character, or substitute one character for another.

kitten becomes sitting in three edits: substitute k→s, substitute e→i, insert g. No two edits can do it, so the distance is 3. Proving that "no two edits can do it" is the hard part, and it is what the table does.

The distance is a true metric: it is 0 only for identical strings, it is the same in both directions (every insert reverses to a delete), and it obeys the triangle inequality. Spell checkers, fuzzy search, DNA alignment and diff tools all rely on it.

  • Distance between equal strings is 0; to or from an empty string, it is the other length
  • It is at least the difference in lengths and at most the longer length
  • Uppercase and lowercase letters count as different unless the input is normalised first
2

The Recurrence

  1. Match (A[i−1] = B[j−1]) – dp[i−1][j−1], no cost.
  2. Substitute – 1 + dp[i−1][j−1]: replace A's last character with B's.
  3. Delete – 1 + dp[i−1][j]: remove A's last character.
  4. Insert – 1 + dp[i][j−1]: append B's last character.

The standard method is the Wagner-Fischer algorithm (1974), a dynamic programming table. Let dp[i][j] be the edit distance between the first i characters of A and the first j characters of B; the answer is dp[m][n].

Base cases: dp[i][0] = i, since a prefix of length i needs i deletions to become empty, and dp[0][j] = j, since j insertions build a prefix of length j.

For any other cell, look only at the last characters, A[i−1] and B[j−1]. If they are equal they line up for free. If not, the last edit was one of three, and each one leaves a smaller problem that is already in the table. Take the cheapest and add 1.

  • Diagonal = match or substitute, above = delete, left = insert
  • Taking a match whenever the letters are equal is always safe
  • Every cell needs only three neighbours
3

Recursion, Memoization and Tabulation

Written as plain recursion, each call makes up to three more, each shrinking one index, so the call tree has roughly 3^(m+n) nodes. Most of them repeat: the call for (3, 4) is reached by many different edit orders.

There are only (m + 1) × (n + 1) distinct subproblems. Memoization stores each result the first time it is computed, giving O(m·n) time and space plus a recursion stack of depth up to m + n. Tabulation fills the same table in a loop with no stack, which is what the code on this page does.

Ways to compute the distance
ApproachTimeSpaceCan recover the edits
Plain recursionO(3^(m+n))O(m+n) stackYes, slowly
MemoizedO(m·n)O(m·n) + stackYes
TabulatedO(m·n)O(m·n)Yes
Two rowsO(m·n)O(n)No
HirschbergO(m·n), about 2× the workO(n)Yes
  • Repeated subproblems are what make DP worth it here
  • Memoization and tabulation do the same O(m·n) work
  • Tabulation avoids deep recursion on long strings
Key reference

Terms, operations, and practical uses

Key terms

  • Edit scriptThe list of edits found by traceback; there can be several of equal length.
  • AlignmentThe two strings written one above the other, with gaps for inserts and deletes.
  • Optimal string alignmentDamerau-Levenshtein where no substring is edited twice.
Implementation

Code in Python, C++ and Java

def edit_distance(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(m + 1):
        dp[i][0] = i          # i deletions to reach an empty string
    for j in range(n + 1):
        dp[0][j] = j          # j insertions from an empty string

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]        # align, cost nothing
            else:
                dp[i][j] = 1 + min(
                    dp[i - 1][j - 1],              # substitute
                    dp[i - 1][j],                  # delete from a
                    dp[i][j - 1],                  # insert into a
                )

    return dp


def two_row(a, b):
    """Only the previous row is ever read, so two rows suffice."""
    previous = list(range(len(b) + 1))

    for i, ca in enumerate(a, start=1):
        current = [i] + [0] * len(b)
        for j, cb in enumerate(b, start=1):
            if ca == cb:
                current[j] = previous[j - 1]
            else:
                current[j] = 1 + min(previous[j - 1], previous[j], current[j - 1])
        previous = current

    return previous[len(b)]


def traceback(a, b, dp):
    i, j, ops = len(a), len(b), []
    while i > 0 or j > 0:
        if i and j and a[i - 1] == b[j - 1] and dp[i][j] == dp[i - 1][j - 1]:
            ops.append(f"keep {a[i - 1]}"); i -= 1; j -= 1
        elif i and j and dp[i][j] == dp[i - 1][j - 1] + 1:
            ops.append(f"sub {a[i - 1]}->{b[j - 1]}"); i -= 1; j -= 1
        elif i and dp[i][j] == dp[i - 1][j] + 1:
            ops.append(f"delete {a[i - 1]}"); i -= 1
        else:
            ops.append(f"insert {b[j - 1]}"); j -= 1
    return ops[::-1]


def main():
    a, b = "kitten", "sitting"
    dp = edit_distance(a, b)

    print("      " + "  ".join(f"{c:>2}" for c in " " + b))
    for i, row in enumerate(dp):
        label = " " if i == 0 else a[i - 1]
        print(f"  {label}  " + "  ".join(f"{v:>2}" for v in row))

    print(f"\nfull table   {dp[len(a)][len(b)]}   O(m*n) space")
    print(f"two rows     {two_row(a, b)}   O(n) space")
    print("edits:", ", ".join(traceback(a, b, dp)))

    a, b = "flaw", "lawn"
    dp = edit_distance(a, b)
    print(f"\n{a} -> {b}: {dp[len(a)][len(b)]}")
    print("edits:", ", ".join(traceback(a, b, dp)))


if __name__ == "__main__":
    main()
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

std::vector<std::vector<int>> editDistance(const std::string& a, const std::string& b) {
    const int m = a.size(), n = b.size();
    std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1, 0));

    for (int i = 0; i <= m; ++i) dp[i][0] = i;  // i deletions
    for (int j = 0; j <= n; ++j) dp[0][j] = j;  // j insertions

    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (a[i - 1] == b[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1];     // align, cost nothing
            } else {
                dp[i][j] = 1 + std::min({dp[i - 1][j - 1],   // substitute
                                         dp[i - 1][j],       // delete
                                         dp[i][j - 1]});     // insert
            }
        }
    }
    return dp;
}

// Only the previous row is ever read, so two rows suffice.
int twoRow(const std::string& a, const std::string& b) {
    std::vector<int> previous(b.size() + 1);
    for (size_t j = 0; j <= b.size(); ++j) previous[j] = j;

    for (size_t i = 1; i <= a.size(); ++i) {
        std::vector<int> current(b.size() + 1, 0);
        current[0] = i;
        for (size_t j = 1; j <= b.size(); ++j) {
            if (a[i - 1] == b[j - 1]) {
                current[j] = previous[j - 1];
            } else {
                current[j] = 1 + std::min({previous[j - 1], previous[j], current[j - 1]});
            }
        }
        previous = current;
    }
    return previous[b.size()];
}

std::string traceback(const std::string& a, const std::string& b,
                      const std::vector<std::vector<int>>& dp) {
    int i = a.size(), j = b.size();
    std::vector<std::string> ops;
    while (i > 0 || j > 0) {
        if (i && j && a[i - 1] == b[j - 1] && dp[i][j] == dp[i - 1][j - 1]) {
            ops.push_back(std::string("keep ") + a[i - 1]); --i; --j;
        } else if (i && j && dp[i][j] == dp[i - 1][j - 1] + 1) {
            ops.push_back(std::string("sub ") + a[i - 1] + "->" + b[j - 1]); --i; --j;
        } else if (i && dp[i][j] == dp[i - 1][j] + 1) {
            ops.push_back(std::string("delete ") + a[i - 1]); --i;
        } else {
            ops.push_back(std::string("insert ") + b[j - 1]); --j;
        }
    }
    std::string out;
    for (auto it = ops.rbegin(); it != ops.rend(); ++it) out += (out.empty() ? "" : ", ") + *it;
    return out;
}

int main() {
    const std::string a = "kitten", b = "sitting";
    const auto dp = editDistance(a, b);

    std::cout << "      ";
    const std::string head = " " + b;
    for (size_t k = 0; k < head.size(); ++k) std::cout << (k ? "  " : "") << std::setw(2) << head[k];
    std::cout << "\n";

    for (size_t i = 0; i < dp.size(); ++i) {
        std::cout << "  " << (i == 0 ? ' ' : a[i - 1]) << "  ";
        for (size_t k = 0; k < dp[i].size(); ++k) std::cout << (k ? "  " : "") << std::setw(2) << dp[i][k];
        std::cout << "\n";
    }

    std::cout << "\nfull table   " << dp[a.size()][b.size()] << "   O(m*n) space\n";
    std::cout << "two rows     " << twoRow(a, b) << "   O(n) space\n";
    std::cout << "edits: " << traceback(a, b, dp) << "\n";

    const std::string c = "flaw", d = "lawn";
    const auto dp2 = editDistance(c, d);
    std::cout << "\n" << c << " -> " << d << ": " << dp2[c.size()][d.size()] << "\n";
    std::cout << "edits: " << traceback(c, d, dp2) << "\n";
    return 0;
}
public class Main {
    private static int[][] editDistance(String a, String b) {
        int m = a.length(), n = b.length();
        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) dp[i][0] = i;  // i deletions
        for (int j = 0; j <= n; j++) dp[0][j] = j;  // j insertions

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];    // align, cost nothing
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j - 1],           // substitute
                              Math.min(dp[i - 1][j], dp[i][j - 1]));    // delete, insert
                }
            }
        }
        return dp;
    }

    // Only the previous row is ever read, so two rows suffice.
    private static int twoRow(String a, String b) {
        int[] previous = new int[b.length() + 1];
        for (int j = 0; j <= b.length(); j++) previous[j] = j;

        for (int i = 1; i <= a.length(); i++) {
            int[] current = new int[b.length() + 1];
            current[0] = i;
            for (int j = 1; j <= b.length(); j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    current[j] = previous[j - 1];
                } else {
                    current[j] = 1 + Math.min(previous[j - 1],
                                  Math.min(previous[j], current[j - 1]));
                }
            }
            previous = current;
        }
        return previous[b.length()];
    }

    static String traceback(String a, String b, int[][] dp) {
        int i = a.length(), j = b.length();
        java.util.LinkedList<String> ops = new java.util.LinkedList<>();
        while (i > 0 || j > 0) {
            if (i > 0 && j > 0 && a.charAt(i - 1) == b.charAt(j - 1) && dp[i][j] == dp[i - 1][j - 1]) {
                ops.addFirst("keep " + a.charAt(i - 1)); i--; j--;
            } else if (i > 0 && j > 0 && dp[i][j] == dp[i - 1][j - 1] + 1) {
                ops.addFirst("sub " + a.charAt(i - 1) + "->" + b.charAt(j - 1)); i--; j--;
            } else if (i > 0 && dp[i][j] == dp[i - 1][j] + 1) {
                ops.addFirst("delete " + a.charAt(i - 1)); i--;
            } else {
                ops.addFirst("insert " + b.charAt(j - 1)); j--;
            }
        }
        return String.join(", ", ops);
    }

    public static void main(String[] args) {
        String a = "kitten", b = "sitting";
        int[][] dp = editDistance(a, b);

        StringBuilder header = new StringBuilder("      ");
        String head = " " + b;
        for (int k = 0; k < head.length(); k++) header.append(k > 0 ? "  " : "").append(String.format("%2c", head.charAt(k)));
        System.out.println(header);

        for (int i = 0; i < dp.length; i++) {
            StringBuilder row = new StringBuilder();
            row.append("  ").append(i == 0 ? ' ' : a.charAt(i - 1)).append("  ");
            for (int k = 0; k < dp[i].length; k++) row.append(k > 0 ? "  " : "").append(String.format("%2d", dp[i][k]));
            System.out.println(row);
        }

        System.out.printf("%nfull table   %d   O(m*n) space%n", dp[a.length()][b.length()]);
        System.out.printf("two rows     %d   O(n) space%n", twoRow(a, b));
        System.out.println("edits: " + traceback(a, b, dp));

        String c = "flaw", d = "lawn";
        int[][] dp2 = editDistance(c, d);
        System.out.printf("%n%s -> %s: %d%n", c, d, dp2[c.length()][d.length()]);
        System.out.println("edits: " + traceback(c, d, dp2));
    }
}
Watch it run

Step through it

Running on A = flaw (rows), B = lawn (columns)

flaw → lawnεlawnεflawcell (i, j) = edit distance betweenthe first i letters of flawand the first j letters of lawn
Step 1

Turn flaw into lawn

Cell (i, j) will hold the fewest edits that turn the first i letters of flaw into the first j letters of lawn. The answer is the bottom-right cell, (4, 4). ε marks the empty prefix.

Output
1 / 12
4

Filling the Table and Tracing Back

The table has m + 1 rows and n + 1 columns; row 0 and column 0 hold the base cases. Fill it row by row, left to right. Each cell needs its left, upper and upper-left neighbours, and in this order all three are already written. Time is O(m·n): one constant-time decision per cell.

The value in the corner says how many edits, not which. To recover them, start at dp[m][n] and repeatedly step to a neighbour that could have produced the current value: diagonal with equal letters means keep, diagonal otherwise means substitute, up means delete, left means insert. Collect the moves and reverse them. When two neighbours tie, either gives a correct sequence of the same length, so a string pair can have several optimal edit scripts.

Practice the table on the Edit Distance problem.

  • Row by row works because dependencies point up and left
  • Traceback walks from the corner to (0, 0) in at most m + n steps
  • Ties mean more than one optimal edit script
5

Two Rows and Hirschberg's Method

Each row reads only the row above, so when only the distance is needed, two arrays of length n + 1 are enough, and a single array plus one saved diagonal value also works. Space drops from O(m·n) to O(n), and it pays to make the shorter string the columns.

The saving is large. Two strings of a million characters need 10^12 cells for the full table, about 4 TB at 4 bytes per cell, but two rows take 8 MB.

The catch is the traceback: it needs the whole table. The Hirschberg algorithm recovers the edits in linear space. It runs the two-row pass forwards over the first half of A and backwards over the second half, finds the column where the optimal path crosses the middle row, and recurses on the two halves. The total work is about twice a single pass.

  • Two rows: O(n) space, distance only
  • Put the shorter string along the columns
  • Hirschberg: O(n) space with the edit script, about 2× the time
6

Variants: Costs, Transpositions and LCS

Weighted edit distance gives each operation its own cost. The recurrence keeps its shape; only the constants change, for example 1 + dp[i−1][j] becomes cost_delete + dp[i−1][j], and a substitution cost can depend on the pair of letters. Keyboard-aware spell checkers make neighbouring keys cheap to substitute, and DNA alignment scores some mismatches lower than others.

The Damerau-Levenshtein distance also allows swapping two adjacent characters for a cost of 1, since "teh" for "the" is one of the most common typos. Under plain Levenshtein, ca → ac costs 2; with transpositions it costs 1. The usual version adds one more case to the recurrence, dp[i−2][j−2] + 1 when the last two characters are swapped. This simpler version is called optimal string alignment, and it never edits a substring twice.

Two restrictions give other well-known measures. Allowing only substitutions on equal-length strings gives the Hamming distance. Allowing only insertions and deletions gives m + n − 2L, where L is the length of the longest common subsequence. For kitten and sitting the LCS is "ittn", L = 4, so the distance is 6 + 7 − 8 = 5. Substitution brings it to 3, because each substitution does the work of one delete plus one insert.

  • Weighted: same table, different costs per operation
  • Damerau-Levenshtein: adjacent swap costs 1, so ca → ac is 1
  • Insert and delete only: m + n − 2 × LCS