How Levenshtein distance fills an edit grid

Short answer: Levenshtein distance is the minimum number of single-character insertions, deletions, and substitutions that turn one string into the other. The DP cell d[i][j] is that distance between the first i characters of the source and the first j characters of the target. It is the minimum of a deletion, an insertion, and a substitution or a free copy when the characters match. The table is O(nm) time and, if only the number is required, O(min(n, m)) memory by keeping two rows. Hirschberg’s algorithm recovers one alignment in linear space.


What the problem actually asks

A direct search over edit scripts is exponential. The optimal script on a pair of prefixes depends only on shorter prefixes: the last operation touches the last character of one string or of both. That is the recurrence. Substitution costs 1 when the characters differ and 0 when they match. Insertion and deletion cost 1. Weights other than 1 are the same recurrence with different constants, and they are no longer the Levenshtein number.

The table also stores the alignment if each cell remembers which argmin won. The path from (n, m) back to (0, 0) is one optimal script. Several paths can tie.


What the algorithm guarantees

d[n][m] is the Levenshtein distance. Time is Θ(nm). A rolling pair of rows computes the number in Θ(min(n, m)) extra memory and discards the path. Hirschberg’s divide-and-conquer recomputes forward and backward rows to find a midpoint of the optimal path and recurses, still in O(nm) time and O(n + m) memory, and returns the alignment. Extra memory for the full table is Θ(nm).

The distance is symmetric. It is not the Damerau-Levenshtein distance, which also allows a transposition of two adjacent characters as one operation. It is not a substring search. Bitap with k errors answers a different question: whether the pattern occurs in the text with distance at most k.


The working steps

  1. Allocate a row d[0][j] = j, the insertions that build the target from empty, and a column d[i][0] = i, the deletions that erase the source.
  2. For i from 1 to n and j from 1 to m, set d[i][j] to the minimum of d[i−1][j] + 1, d[i][j−1] + 1, and d[i−1][j−1] plus 0 if the characters match and 1 if they do not.
  3. d[n][m] is the distance.
  4. To recover a script from the full table, start at (n, m) and step to the predecessor that produced the minimum, emitting a copy, a substitution, an insertion, or a deletion.
  5. If only the number is required, keep the previous row and the current row. If the alignment is required in linear space, use Hirschberg’s midpoint recursion instead of the full table.

The quadratic table is the general distance between two strings. A short pattern in a long text with at most k edits is bitap or a banded diagonal of this table, which runs in O(kn) when the useful cells lie near the diagonal. Filling the whole rectangle for that problem wastes the band. Global alignment with arbitrary gap penalties is Needleman-Wunsch, which generalizes this grid.


Approaches that look simpler and fail

Approach Why it fails when a transposition is charged as one edit
Treat a swap of two adjacent characters as cost 1 That is Damerau-Levenshtein. Classic Levenshtein charges a swap as two substitutions, or as an insertion plus a deletion, depending on the path, and the minimum of those is 2.
Keep one row and also try to walk an alignment backward The discarded rows held the predecessors. One row yields the number. The path needs the table or Hirschberg.
Use the distance as a substring score without a free start The first row of zeros, rather than 0, 1, 2, …, is the start of a local or substring formulation. The classic first row charges for deleting the source prefix.
Fill an n by m table to test a pattern with k errors A band of width k around the diagonal answers that question in O(kn). The full rectangle is the general case.

Local alignment, which may ignore prefixes and suffixes, is Smith-Waterman. Affine gap penalties are Needleman-Wunsch with three states. A short pattern with a small error cap is bitap. Levenshtein is the unit-cost global edit distance.


A working example

This Python fragment fills the Levenshtein grid. An insertion, a deletion, and a substitution each cost 1. The first row and column are the gap costs. It prints 3 for kitten to sitting.

def edit(a, b):
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(
                prev[j] + 1,
                cur[j - 1] + 1,
                prev[j - 1] + (ca != cb),
            ))
        prev = cur
    return prev[-1]

assert edit("kitten", "sitting") == 3
print(edit("kitten", "sitting"))

Where it is used

Levenshtein distance is the edit count behind spell checkers and “did you mean” suggestions. A word processor or a search box asks how many inserts, deletes, and substitutions separate two words. Diff on a whole file is the same grid at line granularity.


When you can drop this algorithm

Drop the full table when the only output is the number and memory is tight. Two rows are enough. Drop it when the operation set includes transpositions or free end gaps. Use the recurrence that states those costs. Keep this grid for unit-cost insertion, deletion, and substitution between two whole strings.


Why this stays published

We publish this so a search for Levenshtein distance returns the three-way recurrence and the linear-space options for the number and the alignment. Levenshtein distance is the quadratic prefix DP of unit-cost insertion, deletion, and substitution, and two rows suffice when the alignment itself is not required.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *