Fewest Edits Between Two Words

HardDynamic Programming≈ 45 min

You can change a word with three kinds of edit, each on one letter:

  • insert a letter anywhere,
  • delete a letter,
  • replace a letter with a different one.

Given the words first and second, return the fewest edits that turn first into second.

Examples

text
first = "horse", second = "ros"         →  3
first = "kitten", second = "sitting"    →  3
first = "", second = "abc"              →  3
first = "same", second = "same"         →  0

"horse" becomes "rorse" (replace h with r), then "rose" (delete the second r), then "ros" (delete e). "kitten" becomes "sitting" by replacing k and e and inserting a g at the end.

Constraints

  • Each word holds between 0 and 300 lowercase letters.
  • Aim for O(n × m), n and m being the two lengths: there are exponentially many ways to edit, and you should not try them all.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.