Edit Distance

Implement minDistance

Given two lowercase words, find the fewest single-character edits — inserting, deleting, or swapping one character for another — needed to turn the first word into the second. Every partial answer only depends on smaller versions of the same question: how many edits does it take to turn some prefix of word1 into some prefix of word2? Once the last pair of letters is decided — either they already agree and cost nothing, or one of the three edits has to cover the mismatch — what's left is exactly the same problem on shorter prefixes. Solving every prefix pair once, smallest first, and reading off three already-known neighbors for each new cell turns an otherwise exponential search into a single pass over a grid.

Example 1:

Input: word1 = "horse", word2 = "ros"

Output: 3

Example 2:

Input: word1 = "abc", word2 = "abc"

Output: 0

Example 3:

Input: word1 = "", word2 = "abc"

Output: 3

+ 7 hidden test cases run on Submit.

Constraints:

  • 0 ≤ word1.length, word2.length ≤ 10
  • word1 and word2 consist of lowercase English letters

word1 =

horse

word2 =

ros