Problems

Edit Distance

hard
hard
strings
dynamic-programming

Return the minimum number of single-character insertions, deletions, or replacements needed to transform word1 into word2.

Input / output

  • Input: word1: string, word2: string
  • Output: integer edit distance

Examples

  1. "horse" to "ros" requires 3 edits.
  2. An empty string to "abc" requires 3 insertions.

Constraints

  • 0 <= word1.length, word2.length <= 500
  • Strings contain lowercase English letters

Follow-up How can you reduce the dynamic-programming memory from quadratic to linear?

Examples

Example 1

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

Example 2

Input: word1 = "intention", word2 = "execution"
Output: 5

Empty source

Input: word1 = "", word2 = "abc"
Output: 3
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.