Menu
CoddyTech

Edit Distance

You get two words, word1 and word2. One edit changes word1 in one of three ways: insert a letter anywhere, delete a letter, or replace a letter with a different one. Return the fewest edits that turn word1 into word2.

Function

minDistance(word1: string, word2: string) → integer
word1string
the word you edit
word2string
the word to reach
Returnsinteger
the fewest inserts, deletes and replaces that turn word1 into word2

Constraints

  • 1 ≤ word1.length ≤ 500
  • 1 ≤ word2.length ≤ 500
  • Both words contain only lowercase English letters.

Examples

Input
word1 = "spot"word2 = "stop"
Output
2
Explanation
Replace the p with t and the t with p: spot becomes stot, then stop. One edit is not enough, because the words differ in two places and an insert or a delete would change the length.

lock icon+21 hidden tests on Submit

challenge icon

Follow-up

Can you also return one shortest list of edits, not only how many there are?

Reset code
def minDistance(word1, word2):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

word1 = "spot"
word2 = "stop"

Expected

2