ntree.ai
ntree.aiEdit Distance

Edit Distance

mediumsolvedattempted

Given two strings word1 and word2, return the fewest operations needed to turn word1 into word2.

One operation is one of these:

  • insert a character
  • delete a character
  • replace a character

Example 1:

Input:  word1 = "horse", word2 = "ros"
Output: 3
Explanation: replace "h" with "r" to get "rorse", delete "r" to get "rose", then delete "e" to get "ros".

Example 2:

Input:  word1 = "intention", word2 = "execution"
Output: 5
Explanation: delete "t", replace "i" with "e", replace "n" with "x", replace "n" with "c" and insert "u".

Constraints:

  • 0 <= length of word1, length of word2 <= 500
  • word1 and word2 hold lowercase English letters only
def minDistance(word1: str, word2: str) -> int:
pass
 

Press Visualise to step through your code.