← Back to Algorithms, page 5

algorithms-0082 · Hard senior

Edit distance: compute the minimum number of single-character insertions, deletions and replacements needed to turn one string into another.

Let d[i][j] be the distance between the first i characters of a and the first j of b. If the last characters match, d[i][j] = d[i-1][j-1]; otherwise it is 1 plus the minimum of delete (d[i-1][j]), insert (d[i][j-1]) and replace (d[i-1][j-1]). Base cases are i and j. Time O(m * n); two rolling rows give O(min(m, n)) space.

Full answer

Problem

Given strings a and b, return the minimum number of operations to convert a into b, where an operation inserts, deletes or replaces one character.

Example: horse to ros takes 3 (replace h with r, delete r, delete e). intention to execution takes 5.

Constraints: 0 <= len(a), len(b) <= 500, lowercase letters.

Brute force

Recursively compare from the front: if the first characters match, move both; otherwise try all three operations and take the best. Without memoization this is O(3^(m+n)). With memoization it becomes the DP below (the test reference uses memoized recursion for clarity).

Optimal approach

Table d of size (m + 1) x (n + 1):

  • d[i][0] = i (delete everything), d[0][j] = j (insert everything).
  • If a[i-1] == b[j-1]: d[i][j] = d[i-1][j-1].
  • Else: d[i][j] = 1 + min(d[i-1][j], d[i][j-1], d[i-1][j-1]).

Row i only depends on row i - 1, so keep two rows, and put the shorter string along the row to use O(min(m, n)) space.

Why it works

Look at the last characters of the two prefixes. In an optimal edit script, either the last character of a is deleted, a character is inserted to produce the last character of b, or the last characters are aligned (free if equal, one replacement if not). Each case leaves a smaller pair of prefixes, and taking the minimum over the cases covers every script. The base cases are the cost of turning a prefix into the empty string and back.

Complexity

O(m * n) time; O(min(m, n)) space with rolling rows, or O(m * n) if the actual edit script must be reconstructed (or use Hirschberg's divide and conquer to reconstruct in linear space).

Code

python
import random
from functools import lru_cache


def edit_distance(a, b):
    """Levenshtein distance (insert, delete, replace each cost 1).
    Two rolling rows: O(len(a) * len(b)) time, O(min(len)) space."""
    if len(a) < len(b):
        a, b = b, a                      # keep the row over the shorter string
    prev = list(range(len(b) + 1))       # distance from "" to b[:j]
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j],       # delete a[i-1]
                                 cur[j - 1],    # insert b[j-1]
                                 prev[j - 1])   # replace
        prev = cur
    return prev[-1]


def brute(a, b):
    @lru_cache(maxsize=None)
    def go(i, j):                        # plain recursion over suffixes, memoised only for speed
        if i == len(a):
            return len(b) - j
        if j == len(b):
            return len(a) - i
        if a[i] == b[j]:
            return go(i + 1, j + 1)
        return 1 + min(go(i + 1, j), go(i, j + 1), go(i + 1, j + 1))
    return go(0, 0)


if __name__ == "__main__":
    assert edit_distance("horse", "ros") == 3
    assert edit_distance("intention", "execution") == 5
    assert edit_distance("", "abc") == 3 and edit_distance("abc", "") == 3
    assert edit_distance("same", "same") == 0
    rng = random.Random(82)
    for _ in range(1000):
        a = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        b = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        d = edit_distance(a, b)
        assert d == brute(a, b) == edit_distance(b, a)
        assert abs(len(a) - len(b)) <= d <= max(len(a), len(b))
    print("all tests passed")

Save as b82_edit_distance.py and run python3 b82_edit_distance.py. It prints all tests passed (Python 3.13.5).

Edge cases

One or both strings empty (the other's length). Identical strings (0). Completely different strings of equal length (the length, all replacements). The distance is symmetric and at least the length difference; the tests check both properties.

Pattern

Two-sequence DP on prefixes, the same family as longest common subsequence. Variants: only insert and delete (equals m + n - 2 * LCS), weighted operation costs, one edit away (O(n) check), and banded DP when only distances up to k matter, which gives O(n * k).

python
import random
from functools import lru_cache


def edit_distance(a, b):
    """Levenshtein distance (insert, delete, replace each cost 1).
    Two rolling rows: O(len(a) * len(b)) time, O(min(len)) space."""
    if len(a) < len(b):
        a, b = b, a                      # keep the row over the shorter string
    prev = list(range(len(b) + 1))       # distance from "" to b[:j]
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j],       # delete a[i-1]
                                 cur[j - 1],    # insert b[j-1]
                                 prev[j - 1])   # replace
        prev = cur
    return prev[-1]


def brute(a, b):
    @lru_cache(maxsize=None)
    def go(i, j):                        # plain recursion over suffixes, memoised only for speed
        if i == len(a):
            return len(b) - j
        if j == len(b):
            return len(a) - i
        if a[i] == b[j]:
            return go(i + 1, j + 1)
        return 1 + min(go(i + 1, j), go(i, j + 1), go(i + 1, j + 1))
    return go(0, 0)


if __name__ == "__main__":
    assert edit_distance("horse", "ros") == 3
    assert edit_distance("intention", "execution") == 5
    assert edit_distance("", "abc") == 3 and edit_distance("abc", "") == 3
    assert edit_distance("same", "same") == 0
    rng = random.Random(82)
    for _ in range(1000):
        a = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        b = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
        d = edit_distance(a, b)
        assert d == brute(a, b) == edit_distance(b, a)
        assert abs(len(a) - len(b)) <= d <= max(len(a), len(b))
    print("all tests passed")

Two-row Levenshtein with the shorter string on the row, checked against memoized recursion and symmetry and bound properties on random strings.

Complexity

Time: O(m * n). Space: O(min(m, n)). Banded DP limits work to O(n * k) when only distances up to k matter.

By level

Fresher: Explains the three operations on the last characters and fills a small table by hand. Writes the full 2D version.

Mid: Compresses to two rows and reconstructs an edit script from the full table. Solves the one-edit-away variant in linear time.

Senior: Discusses banded DP for bounded distances, BK-trees or tries for fuzzy dictionary search, and Hirschberg's method for linear-space reconstruction. Relates the problem to diff tools and sequence alignment with weighted costs.

Key points

  • State over prefixes of both strings
  • Match costs 0, else 1 + min of three moves
  • Base cases are the prefix lengths
  • Two rows give linear space
  • Related to LCS

Common mistakes

  • Mixing up which neighbour is insert and which is delete
  • Wrong base row and column
  • Overwriting the diagonal value too early in a rolling row
  • Forgetting the equal-character shortcut

Follow-ups

  • How would you reconstruct the sequence of edits?
  • How do you check "one edit away" in O(n)?
  • How would you search a dictionary for words within distance 2 of a query?

Tips

  • Explain the three cases with the last characters
  • Fill a small table by hand
  • Mention the two-row optimization

Evaluation rubric

  • Correct recurrence and bases
  • Correct complexity
  • Space optimization
  • Handles empty strings