Edit Distance solution explained
Edit Distance is the smallest number of single-character insertions, deletions and replacements that turn one word into another, also called the Levenshtein distance. Fill a table where cell (i, j) is the distance between the first i letters of one word and the first j of the other: matching letters copy the diagonal, otherwise take one plus the smallest of the three neighbors that stand for delete, insert and replace. The first row and column count pure insertions and deletions, and the whole table costs O(m · n).
By Evin JohnPublished 8 min read
The problem, restated
A spell checker sees a typed word and a dictionary word. It wants to know how close they are, measured as the fewest single-letter fixes. A fix is one of three things: insert one letter anywhere, delete one letter, or replace one letter with another. Each fix costs one. Return the fewest fixes that turn the typed word into the dictionary word.
| From | To | Distance | One shortest set of edits |
|---|---|---|---|
| lamp | lame | 1 | Replace p with e |
| table | able | 1 | Delete the t |
| flour | flower | 2 | Replace u with w, insert e |
| form | from | 2 | Swapping o and r takes two replacements here |
| (empty) | sky | 3 | Insert all three letters |
Why it is a staple
Edit distance sits behind spelling suggestions, fuzzy search, DNA alignment and diff tools, so interviewers can frame it many ways. As a question it checks whether you can handle three competing choices in one recurrence and whether you get the base cases right. The base row and column are where most bugs hide, because they are not zeros as they are in many other grid problems.
Follow-ups
- Show the edits, not just the count. Keep the table and walk back from the corner.
- Different costs per operation. Replace each 1 with the cost of that operation; the structure stays the same.
- Are the two words at most one edit apart? A single linear scan answers it without a table: walk both words until the first difference, then compare the rest under each of the three possible fixes.
- Count a swap of neighbors as one edit. That is the Damerau variant, which adds a fourth case looking two cells back diagonally. Under it, form to from becomes 1.
- Only care if the distance is at most k. Fill only a band of width 2k + 1 around the diagonal for O(n · k) time.
Brute force
Compare the last letters of both words. If they match, leave them alone and solve the shorter words. If not, try all three fixes for that last position and keep the cheapest: delete the last letter of the first word, insert the second word's last letter, or replace one with the other. Each mismatch branches three ways, so plain recursion is exponential, but there are only (m + 1) · (n + 1) distinct pairs of prefixes.
def edit_distance_slow(a, b):
if not a:
return len(b)
if not b:
return len(a)
if a[-1] == b[-1]:
return edit_distance_slow(a[:-1], b[:-1])
return 1 + min(
edit_distance_slow(a[:-1], b), # delete from a
edit_distance_slow(a, b[:-1]), # insert into a
edit_distance_slow(a[:-1], b[:-1]), # replace
)The table
Let dp[i][j] be the distance from the first i letters of a to the first j letters of b. The first column is 0, 1, 2 and so on, because turning i letters into nothing takes i deletions. The first row is the same for insertions. For each other cell, matching letters cost nothing and inherit the diagonal. Otherwise, the cell above means a[i - 1] was deleted, the cell to the left means b[j - 1] was inserted, and the diagonal means one letter was replaced; take the cheapest and add one.
| empty | g | u | m | |
|---|---|---|---|---|
| empty | 0 | 1 | 2 | 3 |
| m | 1 | 1 | 2 | 2 |
| u | 2 | 2 | 1 | 2 |
| g | 3 | 2 | 2 | 2 |
def edit_table(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i # delete every letter
for j in range(n + 1):
dp[0][j] = j # insert every letter
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]
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
return dp
def edit_distance(a, b):
return edit_table(a, b)[len(a)][len(b)]In the mug to gum table, the u in the middle matches, so its cell copies the diagonal value 1. The corner ends at 2: replace the m with g and the g with m, keeping the u. Reading the path back through the table is exactly how the edit list is recovered.
Recovering the edits
def edit_steps(a, b):
dp = edit_table(a, b)
i, j, steps = len(a), len(b), []
while i > 0 or j > 0:
if i > 0 and j > 0 and a[i - 1] == b[j - 1]:
steps.append(("keep", a[i - 1]))
i, j = i - 1, j - 1
elif i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + 1:
steps.append(("replace", a[i - 1], b[j - 1]))
i, j = i - 1, j - 1
elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
steps.append(("delete", a[i - 1]))
i -= 1
else:
steps.append(("insert", b[j - 1]))
j -= 1
return steps[::-1]One row for the number only
Each cell reads the cell above, the cell to the left and the diagonal, so one row is enough with a saved diagonal. The detail people miss is the base column: at the start of row i, the leftmost cell must become i, and the old leftmost value becomes the first diagonal.
function minDistance(a, b) {
const row = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
let diagonal = row[0]; // dp[i - 1][0]
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const above = row[j];
if (a[i - 1] === b[j - 1]) row[j] = diagonal;
else row[j] = 1 + Math.min(above, row[j - 1], diagonal);
diagonal = above;
}
}
return row[b.length];
}Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Plain recursion | Exponential (up to three branches per mismatch) | O(m + n) stack |
| Full table with step recovery | O(m · n) | O(m · n) |
| One row | O(m · n) | O(min(m, n)) if the shorter word is the row |
| Banded table for distance at most k | O(n · k) | O(n · k) or O(k) |
Edge cases
- One or both words empty: the distance is the other word's length.
- Identical words: 0.
- Words with no letters in common and equal length: one replacement per letter.
- Very different lengths: at least the length difference in insertions or deletions.
Common mistakes
- Filling the first row and column with zeros, copied from LCS-style tables.
- Adding 1 even when the letters match.
- Mixing up which neighbor means insert and which means delete, which only matters when you print the steps or use different costs.
- In the one-row version, forgetting to set row[0] = i at the start of each row.
- Assuming a swap of two neighbors is one edit when only the three basic operations are allowed.
How to explain it out loud
Fictional example
- Candidate
- I will define cell i, j as the cost to turn the first i letters of the first word into the first j letters of the second. Turning i letters into nothing costs i, so the first column counts up, and the first row does the same.
- Candidate
- If the current letters match, I copy the diagonal. If not, I pay one and pick the cheapest of three: above means I deleted, left means I inserted, diagonal means I replaced.
- Candidate
- That is m times n. If you want the actual edits I keep the table and trace back; if you only want the number, one row with a saved diagonal works.
Related problems
Longest Common Subsequence fills the same grid with a maximum; with only inserts and deletes allowed, edit distance equals m + n minus twice the LCS. Unique Paths is the gentlest version of a grid fill. Word Break is a one-dimensional string DP that pairs well with this one in a study session.
Practicing with Natively
Mapping the three neighbors to the three operations is the step to drill until it is automatic. During practice, Natively on Mac or Windows can read the problem from a screenshot and suggest how the recurrence might look, which you can check against your own once you have tried it, and the transcript of your mock round shows whether you explained the base row before filling the middle. Read about the AI interview assistant.
Questions people ask
How do you solve the Edit Distance problem?
Fill a table where cell (i, j) is the cost of turning the first i letters of one word into the first j of the other. The first row and column count up from 0. Matching letters copy the diagonal; otherwise add 1 to the smallest of above, left and diagonal.
What do the three neighbors mean in edit distance?
The cell above stands for deleting a letter from the first word, the cell to the left for inserting a letter from the second word, and the diagonal for replacing one letter with the other.
What is the time complexity of Edit Distance?
O(m · n) time for words of length m and n. The full table uses O(m · n) memory; one row with a saved diagonal uses O(min(m, n)) but cannot list the edits.
Is edit distance the same as Levenshtein distance?
Yes, when the allowed operations are inserting, deleting and replacing a single character at cost 1 each. Allowing a swap of two neighboring letters gives the Damerau variant.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
