Edit Distance (the distance between strings)

Edit Distance (also known as the Levenshtein distance) is a classic dynamic programming problem that measures the smallest number of operations needed to turn one string into another.

The allowed operations are:

  • inserting a character,
  • deleting a character,
  • replacing one character with another.

Each operation costs 1.


Problem definition

Two strings are given:

  • s – the source string,
  • t – the target string.

Find the smallest number of operations that turn the string s into the string t.

Example:

  • s = "kitten"
  • t = "sitting"

The result is 3:

kitten → sitten   (replace k with s)
sitten → sittin   (replace e with i)
sittin → sitting  (insert g at the end)

Why dynamic programming?

If we look at the prefixes of the strings (their initial parts), the problem naturally breaks down into smaller subproblems: to turn "kitten" into "sitting", it is enough to know the solutions for shorter prefixes, for example "kitte" → "sittin".

Edit Distance has both properties needed for dynamic programming:

  • optimal substructure – the optimal solution consists of optimal solutions for shorter prefixes,
  • overlapping subproblems – the same pair of prefixes appears in many different branches of the recursion.

DP state

We define:

dp[i][j] = the smallest number of operations
           that turn the first i characters of s
           into the first j characters of t

The final answer is dp[n][m], where n and m are the lengths of the strings.


Base cases

  • dp[0][j] = j – from the empty string we get to j characters with j insertions,
  • dp[i][0] = i – from i characters we get to the empty string with i deletions.

Transition (DP relation)

We look at the last characters of the prefixes, s[i-1] and t[j-1]. If they are equal, we need no new operation:

dp[i][j] = dp[i-1][j-1]

If they are different, we choose the cheapest of the three operations:

dp[i][j] = 1 + min(
    dp[i-1][j],     // delete the character s[i-1]
    dp[i][j-1],     // insert the character t[j-1]
    dp[i-1][j-1]    // replace s[i-1] with t[j-1]
)
How to remember the transitions?
  • Up (dp[i-1][j]): a character from s was deleted, and t did not move.
  • Left (dp[i][j-1]): we inserted a character from t, and s did not move.
  • Diagonal (dp[i-1][j-1]): both characters are processed, by a replacement or with no change.

DP table for the example kitten → sitting

The rows correspond to the prefixes of the string s = "kitten", and the columns to the prefixes of the string t = "sitting". The symbol ε stands for the empty string. The table is filled row by row, from left to right, because each cell depends only on the cells above, to the left and up-left.

εsitting
ε01234567
k11234567
i22123456
t33212345
t44321234
e55432234
n66543323

The answer is in the bottom right corner: dp[6][7] = 3. For example, the cell dp[1][1] (k → s) is 1, because the characters are different and the smallest of the three neighboring values is 0.


Implementation (C++)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>   // for the min function
using namespace std;

// The smallest of three numbers
int min3(int a, int b, int c) {
    return min(a, min(b, c));
}

int main() {
    string s, t;
    cin >> s >> t;

    int n = s.size();
    int m = t.size();

    // dp[i][j] - the smallest number of operations to turn the first i characters
    // stringa s pretvori u prvih j znakova stringa t.
    // vector instead of the array dp[n + 1][m + 1], because a variable-length
    // array is not standard C++ and does not fit on the stack for long strings.
    vector<vector<int>> dp(n + 1, vector<int>(m + 1));

    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            if (i == 0)
                dp[i][j] = j;                    // ubacujemo j znakova
            else if (j == 0)
                dp[i][j] = i;                    // we delete i characters
            else if (s[i - 1] == t[j - 1])
                dp[i][j] = dp[i - 1][j - 1];     // the last characters are the same
            else
                dp[i][j] = 1 + min3(
                    dp[i - 1][j],     // delete the character s[i-1]
                    dp[i][j - 1],     // ubacivanje znaka t[j-1]
                    dp[i - 1][j - 1]  // replace s[i-1] with t[j-1]
                );
        }
    }

    cout << "Edit distance: " << dp[n][m] << endl;
    return 0;
}
Why a vector and not int dp[n + 1][m + 1]?

An array whose length is given by a variable is not part of standard C++, and it is created on the stack, which is small (usually 8 MB). For two strings of length 3000 the table takes about 36 MB and the program crashes (segmentation fault). A vector is created in dynamic memory and does not have this problem. Also, the min function needs the header <algorithm>.


Memory optimization: two rows instead of the whole table

Computing row i needs only row i − 1. So it is enough to keep two rows, and the memory drops from O(n · m) to O(m).

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    string s, t;
    cin >> s >> t;

    int n = s.size();
    int m = t.size();

    // Row i needs only row i - 1, so we keep two rows.
    vector<int> prethodni(m + 1), tekuci(m + 1);

    // Row i = 0: from the empty string to the first j characters of t
    for (int j = 0; j <= m; j++)
        prethodni[j] = j;

    for (int i = 1; i <= n; i++) {
        tekuci[0] = i;   // j = 0: we delete all i characters

        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1])
                tekuci[j] = prethodni[j - 1];
            else
                tekuci[j] = 1 + min({prethodni[j],        // brisanje
                                     tekuci[j - 1],       // ubacivanje
                                     prethodni[j - 1]});  // zamena
        }

        swap(prethodni, tekuci);   // the current row becomes the previous one
    }

    // After the last swap the result is in the array prethodni
    cout << "Edit distance: " << prethodni[m] << endl;
    return 0;
}

This variant gives only the number of operations. If you also need to print which operations were performed, the whole table is needed, because the path is reconstructed backwards from dp[n][m]. That is exactly what the interactive example below does.


Time and space complexity

  • Time complexity: O(n · m)
  • Space complexity: O(n · m) with the whole table, or O(m) with two rows

where n and m are the lengths of the strings.

Interactive example: the DP table and the sequence of operations

Enter two short strings (at most 12 characters) and press the button. The filled DP table will be shown, with the path that leads to the solution marked and the order of the operations.

Practical applications

Edit Distance is used in:

  • spell checking and suggesting corrections (“Did you mean...?”),
  • search that tolerates typing mistakes,
  • bioinformatics, for comparing DNA sequences,
  • natural language processing and comparing the similarity of texts.

Connection with other DP problems

  • Longest Common Subsequence (LCS) – the same table structure over two strings; if only deletions and insertions are allowed, the distance is n + m − 2·LCS.
  • Grid DP – each cell depends on the neighbors above, to the left and diagonally.
  • String alignment problems (sequence alignment).

Understanding this problem is a big step towards mastering advanced dynamic programming.

The example and visualization of the problem Coin Change – the number of ways to form a sum, which used to be on this page, are covered on the page DP: the Coin Change problem.