Edit Distance

50 min · minDistance()

A typo fixer needs more than a yes-or-no answer. It needs to know how far one word is from another.

Given lowercase strings word1 and word2, return the fewest single-character edits needed to turn word1 into word2. You may perform three kinds of edit:

  • insert one character,
  • delete one character, or
  • replace one character with another.

The Levenshtein distance is the minimum number of those edits needed for a transformation. Each edit costs one, and you may apply edits in any order.

An empty string is valid. Turning an empty string into a word requires one insertion per character; turning a word into an empty string requires the matching number of deletions.

Constraints

  • 0 <= word1.length <= 200
  • 0 <= word2.length <= 200
  • Both strings contain only lowercase English letters.

Hints

Compare the next characters

If word1[i] == word2[j], those characters already agree, so move past both at no cost. Otherwise, model the first edit and solve the remaining suffixes.

Name the three branches

An insertion advances only j, a deletion advances only i, and a replacement advances both. Add one to the cheapest resulting state.

Build from empty prefixes

Let a table cell store the distance between two prefixes. Row zero and column zero are known: converting to or from an empty prefix costs the other prefix's length.

Follow-up

Could you return one shortest sequence of edits, not just its length?

Visible cases

Examples

Example 1

ready
Input
word1 = "horse"
word2 = "ros"
Expected
3
Why
three edits are enough, and no two-edit route exists

Example 2

ready
Input
word1 = "intention"
word2 = "execution"
Expected
5
Why
the shortest transformation uses five edits

Example 3

ready
Input
word1 = ""
word2 = "abc"
Expected
3
Why
insert a, b, and c

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite