Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Edit distance between two strings

Hard · Target 30 minutes · Dynamic programming · Type asked atGoogleAmazon

Given two strings a and b, return the smallest number of single-character operations that turn a into b. The allowed operations are inserting a character, deleting a character and replacing one character with another.

Examples

InputOutputWhy
a = "horse", b = "ros"3horse → rorse (replace h) → rose (delete r) → ros (delete e).
a = "kitten", b = "sitting"3Two replacements and one insertion.
a = "abc", b = ""3Delete everything.

Constraints

  • 0 ≤ |a|, |b| ≤ 500
  • Lowercase letters

Hints

Hint 1

Look at the last characters. If they are equal, they can be left alone, and the problem shrinks to the two shorter prefixes.

Hint 2

If they differ, the last operation is one of three: replace a's last character with b's, delete a's last character, or insert b's last character. Each leaves a smaller problem on prefixes.

Hint 3

Let d[i][j] be the distance between the first i characters of a and the first j of b. Fill the table from d[0][j] = j and d[i][0] = i; only the previous row is needed at any time.

Where people lose marks

  • Treating a match as free but still adding 1 for it. When the last characters are equal, the cell copies its diagonal neighbour with no cost.
  • Overwriting the diagonal value too early when compressing to one row: save d[i−1][j−1] before writing d[i][j−1].
  • Forgetting the edges. d[i][0] = i is not zero; turning "abc" into "" costs 3.
  • Indexing the strings with the table's indices: d[i][j] looks at a[i−1] and b[j−1], because row and column 0 stand for the empty prefix.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.