Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 11  /  EDIT DISTANCE

The Typo Fixer.

Watch the explainer

How far is kitten from sitting? Not in letters — in edits. Watch a grid work out the fewest insert, delete, and replace moves to turn one word into the other, one cell at a time, then trace the cheapest path.

THE GIST · 20 SECONDS

Edit distance (the Levenshtein distance) is the fewest single-character insert / delete / replace edits to turn string A into string B. Build a grid: dp[i][j] is the distance between the first i letters of A and first j of B. If the letters match, copy the diagonal; else take 1 + the smallest of the diagonal (replace), up (delete), and left (insert). The answer waits in the bottom-right.

  • Insertadd a letter (← left)
  • Deletedrop a letter (↑ up)
  • Replaceswap a letter (↖ diag)
  • Matchfree — copy the diagonal

Hit Step to fill the next cell — or Play and watch the whole grid compute, then trace the cheapest edits.

UNDER THE HOOD

What you just played, written down

Every cell asks one small question and reuses answers already on the grid. That reuse — solving each subproblem once — is dynamic programming.

How edit distance thinks — four moves

  1. Define the cell. dp[i][j] = edits to turn A's first i letters into B's first j letters.
  2. Seed the edges. dp[i][0] = i (delete everything), dp[0][j] = j (insert everything). Turning a word into "" costs its length.
  3. Match is free. If A[i-1] == B[j-1], the last letters already agree — copy the diagonal, dp[i-1][j-1]. No edit.
  4. Otherwise pay 1. dp[i][j] = 1 + min( diagonal ↖ replace, up ↑ delete, left ← insert ). The answer is the bottom-right corner.
WHY THE DIRECTIONS MEAN THOSE EDITS

Moving ↖ diagonally consumes one letter of both words — a replace (or free match). Moving ↑ consumes a letter of A only — a delete. Moving ← consumes a letter of B only — an insert.

The whole thing in code

def edit_distance(a, b):
    m, n = len(a), len(b)
    dp = [[0]*(n+1) for _ in range(m+1)]
    # base cases: turn a word into ""
    for i in range(m+1): dp[i][0] = i
    for j in range(n+1): dp[0][j] = j
    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]      # match - free
            else:
                dp[i][j] = 1 + min(
                    dp[i-1][j-1],            # replace ↖
                    dp[i-1][j],              # delete  ↑
                    dp[i][j-1])              # insert  ←
    return dp[m][n]
TIMEO(m·n)every cell once
SPACEO(m·n)O(min) for value only
TWO ROWS ARE ENOUGH — FOR THE NUMBER

Each cell only reads the current and previous row, so you can drop to O(min(m,n)) space if you just want the distance. Recovering the actual edits needs the full grid (or Hirschberg's divide-and-conquer).

⚠ Ties = many optimal paths

When the diagonal, up, and left neighbors tie, there are several cheapest edit sequences. The traceback here prefers match/replace, then delete, then insert — any consistent rule finds a minimum.

↔ Its relatives

Longest Common Subsequence is the same grid with different rules; Needleman–Wunsch is edit distance with weighted gaps for DNA; Damerau–Levenshtein adds a transposition edit.

★ Where it's used

Spell-check & autocorrect, fuzzy search, diff tools, DNA/protein alignment, plagiarism detection, and scoring speech recognition against a reference.

The picture: the grid and its cheapest path

""ros""0123h1123o2212r3222s4332e5443one cheapest path: 3 edits1. replace h with r2. keep o3. delete r4. keep s5. delete e
The table for turning horse into ros. Row i, column j holds the distance between the first i letters of one word and the first j of the other. The highlighted cells are one cheapest path from the top-left corner to the bottom-right cell, which holds 3. A diagonal step is a replace or a free match, a step down is a delete, a step right is an insert.

Worked example, step by step

Turn kitten into sitting. The grid has 7 × 8 = 56 cells, but only the cells on one cheapest path matter for the answer. Each row below is such a cell: the letters being compared (kitten letter / sitting letter), the three neighbours the cell looks at, and the value it ends up with.

Cell (i, j)LettersDiagonalUpLeftValueEdit
(1, 1)k / s0111replace
(2, 2)i / i1221match (free)
(3, 3)t / t1221match (free)
(4, 4)t / t1221match (free)
(5, 5)e / i1222replace
(6, 6)n / n2332match (free)
(6, 7)– / g3423insert

Read the Edit column top to bottom and you have the script: replace k with s, keep itt, replace e with i, keep n, insert g. That is 3 edits, and no path through the grid is cheaper. Notice that a match copies the diagonal and ignores the other two neighbours, even when one of them is a point lower (a neighbour can be at most one below the diagonal); the free move is always at least as good, because it uses up a letter on both sides at no cost. Notice also that the values along the path never drop: they stay the same on a match and rise by one on an edit, which is why the bottom-right cell is the total. The memoised table needed 56 cells. The same recursion with no memo, run on these two words, makes 3032 calls, because it re-solves the same prefix pairs again and again.

Complexity and trade-offs

Let m and n be the lengths of the two words.

CaseTimeSpaceWhy
Full grid (this page)O(m·n)O(m·n)Every cell once, O(1) each. Keeps the whole table, so you can trace the edits back.
Two rowsO(m·n)O(min(m, n))A cell reads only the row above and the cell to its left. Gives the number, not the edits.
HirschbergO(m·n)O(min(m, n))Divide and conquer on the middle row; recovers the actual edit script in linear space, at roughly twice the time.
Cut-off at k editsO(k·min(m, n))O(k)Only cells within k of the diagonal can matter when you only care whether the distance is at most k.
Plain recursion, no memoexponentialO(m + n) stackSame recurrence, no reuse. 3032 calls for kitten and sitting against 56 cells.

The cost that bites is the quadratic one. Two strings of 100,000 characters make a grid of 10,000,200,001 cells; even at one byte per cell that is about ten gigabytes, which is why the two-row and Hirschberg versions exist. The time is harder to avoid: for general inputs no algorithm is known that is much faster than quadratic, so practical systems avoid comparing everything with everything. They cap the distance (the cut-off row) or filter candidates first and only run the grid on the survivors.

Common mistakes

  • Leaving the first row and column at zero

    Without dp[i][0] = i and dp[0][j] = j, turning a word into the empty string looks free. edit_distance("abc", "") returns 0 instead of 3, and horse to ros comes out as 2 instead of 3.

  • Indexing the word with i instead of i − 1

    The grid has one extra row and column for the empty prefix, so cell (i, j) compares a[i-1] with b[j-1]. Using a[i] shifts every comparison by one letter, and on the last row it reads past the end of the word (an IndexError in Python, undefined in JavaScript, so the match test is silently false).

  • Dropping the replace move

    If a cell only looks at up and left, you are computing insert/delete distance. For kitten and sitting that gives 5, not 3, because each replace now costs a delete plus an insert.

  • Charging for a match

    Writing 1 + min(...) for every cell, equal letters included, makes the grid pay for letters that already agree. kitten to sitting comes out as 7 instead of 3.

  • Using the two-row version and then asking for the edits

    Once you throw rows away you cannot walk back from the corner. If the caller wants the edit script, keep the full grid or use Hirschberg’s method; do not bolt a traceback onto the rolling rows.

Where this shows up

  • Fuzzy search and “did you mean”

    Spell checkers rank candidate words by their distance from what was typed. Search engines such as Lucene-based ones define a fuzzy query by a maximum edit distance, and PostgreSQL ships a levenshtein() function in its fuzzystrmatch extension.

  • Speech recognition scoring

    Word error rate is the edit distance between the reference transcript and the recogniser’s output, taken over words rather than letters, divided by the length of the reference. For “the cat sat on the mat” heard as “the cat sit on mat” it is 2 edits over 6 words, 33.3%.

  • Sequence alignment

    Aligning DNA or protein sequences is the same grid with weighted costs for each kind of gap and mismatch, which is the Needleman–Wunsch idea the page mentions.

  • Data cleaning and deduplication

    Matching misspelled names or addresses against a master list is usually a cheap filter (same first letters, similar length) followed by an edit distance on the few candidates left.

SOLVE IT YOURSELF

Solve it: edit distance

This one is yours to write — in Python or TypeScript, running for real in your browser. Fill the DP table and return the bottom-right cell. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement edit_distance(a, b): return the minimum number of single-character insertions, deletions, and replacements to turn a into b. Build the (m+1) × (n+1) DP table and return dp[m][n].

HINTS — 4 IDEAS
  1. Base cases: dp[i][0] = i and dp[0][j] = j — turning a word into "" costs its length.
  2. If a[i-1] == b[j-1], the letters match: dp[i][j] = dp[i-1][j-1] (no edit).
  3. Otherwise dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) — replace, delete, insert.
  4. The answer is the bottom-right cell, dp[m][n].
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In the DP grid, what does cell dp[i][j] represent?

    Answer: The edit distance between A’s first i letters and B’s first j letters — Each cell is a subproblem: the minimum edits to turn the first i characters of A into the first j characters of B. The final answer is the bottom-right cell, dp[m][n].

  2. When the current characters A[i-1] and B[j-1] match, what is dp[i][j]?

    Answer: dp[i-1][j-1] (copy the diagonal, no edit) — A match needs no edit, so you inherit the diagonal value dp[i-1][j-1] unchanged. Only a mismatch costs 1 plus the best neighbor.

  3. What is the time complexity of the standard edit-distance DP?

    Answer: O(m · n) — There are (m+1)·(n+1) cells and each is computed in O(1) from three neighbors, so filling the whole table is O(m·n).

FAQ

Edit distance, answered

What is edit distance?

The Levenshtein distance — the fewest single-character insert, delete, and replace edits to turn one string into another. Turning kitten into sitting takes 3: replace k→s, replace e→i, insert g.

How does the DP table work?

dp[i][j] is the distance between A's first i letters and B's first j. The first row/column are base cases; every other cell is built from its diagonal, up, and left neighbors.

What's the recurrence?

If a[i-1]==b[j-1], dp[i][j]=dp[i-1][j-1] (match, free). Otherwise dp[i][j]=1+min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) — replace, delete, insert. Answer: dp[m][n].

What's the complexity?

O(m·n) time and space. For just the number you can keep two rows — O(min(m,n)) space — but recovering the edits needs the full grid.

Where is it used?

Spell-check & autocorrect, fuzzy search, diff tools, DNA/protein alignment (Needleman–Wunsch), plagiarism detection, and speech-recognition scoring.

RESULT

—

Next → keep the diagonal-only rule and you're computing the Longest Common Subsequence; add gap weights and it becomes DNA sequence alignment.

▶  Watch it explained

Edit Distance: Turn SUNDAY into SATURDAY

Finished this one? 0 / 99 Algorithms done
NextThe Patient Router: Bellman-Ford Closest algorithm to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms