download

Edit distance between two words: what does each table cell mean?

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

Question

A shop's search box should suggest close matches for typos. Write edit_distance(a, b): the fewest single-letter edits that turn word a into word b. An edit inserts, deletes or replaces one letter. Then explain what each cell of your table means.

"PYTHON"
edit_distance("cake", "back")   # 3
edit_distance("cart", "chart")  # 1, insert h
edit_distance("", "shoe")       # 4
"CODE · PYTHON"
def edit_distance(a, b):
    ...
Show hints (3)
  1. "SMALLER PIECES"

    Let cell [i][j] be the fewest edits that turn the first i letters of a into the first j letters of b. What goes in row 0 and column 0?

  2. "THE LAST LETTERS"

    Look at the last letter of each prefix. If they match, they need no edit. If not, the last edit was a delete, an insert or a replace.

  3. "THE FORMULA"

    If a[i - 1] == b[j - 1], copy the cell up and to the left. Otherwise take 1 plus the smallest of up (delete), left (insert) and up-left (replace). The answer is the bottom-right cell.

Show checked explanation

Fill a table where cell [i][j] is the fewest edits that turn the first i letters of a into the first j letters of b. Row 0 and column 0 count pure inserts and deletes. If the last letters match, copy the up-left cell. Otherwise take 1 plus the smallest of the up, left and up-left cells. The answer is the bottom-right cell.

"SOLUTION · PYTHON"
def edit_distance(a, b):
    # dist[i][j]: fewest edits that turn a[:i] into b[:j]
    dist = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    dist[0] = list(range(len(b) + 1))
    for i in range(len(a) + 1):
        dist[i][0] = i
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dist[i][j] = dist[i - 1][j - 1]
            else:
                dist[i][j] = 1 + min(dist[i - 1][j],      # delete
                                     dist[i][j - 1],      # insert
                                     dist[i - 1][j - 1])  # replace
    return dist[len(a)][len(b)]


print(edit_distance("cake", "back"))
print(edit_distance("cart", "chart"))
print(edit_distance("", "shoe"))
"OUTPUT"
3
1
4

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Row 0 and column 0 stand for an empty prefix. Turning "" into "bac" takes 3 inserts. Turning "cak" into "" takes 3 deletes.

Here is the table for cake → back. Rows are prefixes of cake, and columns are prefixes of back:

""back
""01234
c11223
a22123
k33222
e44333

To fill a cell, look at the last letter of each prefix. If they match, they need no edit, so copy the cell up and to the left. Row a, column a is 1, because ca → ba costs the same as c → b. If they differ, the last edit was one of three, and you take the cheapest:

  • replace the letter: up-left + 1;
  • delete the last letter of the a prefix: up + 1;
  • insert the last letter of the b prefix: left + 1.

Row k, column k is 2. The letters match, so it copies ca → bac, which is 2: replace c with b, then insert c. In the bottom-right cell, e and k differ. The cheapest option is 2 + 1, for example deleting e from the cell above.

So cake → back takes 3 edits: replace c with b, insert c, delete e. The table has (m + 1) × (n + 1) cells for words of length m and n, and each takes O(1). That is O(m·n) time and memory.

Common mistakes

  • Filling row 0 and column 0 with zeros. Then edit_distance("", "shoe") returns 0, though it needs 4 inserts.
  • Adding 1 even when the letters match. Then edit_distance("cake", "cake") returns 4 instead of 0.
  • Comparing a[i] with b[j]. Row i stands for the first i letters, so its last letter is a[i - 1]. With a[i] you compare the wrong letters, and at the last column b[j] runs past the end: IndexError.
  • Counting the positions where the letters differ. That allows only replaces. cart and chart differ at 3 of the first 4 positions, but one insert fixes them.

Follow-up questions

  • "Can you use less memory?" Yes. Each row needs only the row above it, so keep two rows. Memory drops to O(n), or O(min(m, n)) if the shorter word goes in the columns. Time stays O(m·n). With only two rows you can't walk back to list the edits.
  • "How do you list the actual edits?" Start at the bottom-right cell and walk back. At each cell, move to a neighbour that explains its value: up-left for a match or a replace, up for a delete, left for an insert. For cake → back, one path gives replace c with b, insert c, delete e.
  • "A user types shose for shoes. Why is the distance 2?" Swapping two neighbouring letters costs two replaces. Add a swap rule: if the last two letters are swapped, also try the cell two up and two left, plus 1. Then shose → shoes costs 1. This is optimal string alignment. Full Damerau-Levenshtein also lets you insert between swapped letters: ca → ac → abc costs 2, but 3 with the simple rule.

What a strong answer covers

Defines the cell in words before coding, including the empty-prefix row and column. Explains the match case and the three edit cases. Gives O(m·n) time, and cuts memory to two rows when asked.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.