Skip to the solution
HardDSA15 min read

How do you compute the edit distance between two strings?

610 views

The problem

Question presented to candidate: "Given two words, return the minimum number of operations to turn the first into the second, where an operation inserts, deletes or replaces one character. Explain your table, then code it in Python."

What a strong answer should cover:

  • The state dp[i][j] = fewest edits turning the first i characters of word1 into the first j of word2.
  • The base cases dp[i][0] = i and dp[0][j] = j (not zeros), and why.
  • The transition: equal characters copy the diagonal; otherwise 1 + min(diagonal = replace, up = delete, left = insert).
  • O(m·n) time and space; O(min(m, n)) space with two rows when only the number is needed; walking back for the edit script.
  • Python details: building the table with a list comprehension, min() over three values, and that difflib.SequenceMatcher is not a Levenshtein distance.

Clarifying questions expected:

  • Are all three operations allowed, and do they all cost 1?
  • Does swapping two adjacent characters count as one edit?
  • Do you need the edit operations or just the count?

Code / implementation expected: Yes — a bottom-up table in Python; mention the two-row optimisation and how to recover the operations.

  • dp
  • strings

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read · 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonEdit distance table, distances and the edit script
PythonNaive recursion vs table, the LCS link, and two rows

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 145 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Burst Balloons: why does DP over intervals (not balloons) work?

Continue