You are given two words, word1 and word2. You may change word1 one letter at a time with three kinds of edits: insert a letter anywhere, delete a letter, or replace a letter with a different one.
Return the smallest number of edits that turns word1 into word2.
Example 1
Input: word1 = "cap", word2 = "ape" Output: 2 Why: delete c to get "ap", then insert e at the end
2 more examples and the constraints
Example 2
Input: word1 = "sunday", word2 = "saturday" Output: 3 Why: insert a and t after s, replace n with r
Example 3
Input: word1 = "", word2 = "abc" Output: 3 Why: from an empty word, insert all three letters
Constraints
- 0 ≤ length of word1, length of word2 ≤ 500
- Both words use only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m·n)
- Bottom-up tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two words of 500 letters | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m·n) | Passes; deep recursion | |
| Bottom-up table | O(m·n) | Best; no recursion |
m = length of word1, n = length of word2.
Edge cases to test
- An empty word. Example 3: the answer is the length of the other word.
- Both empty. Zero edits.
- The same word. Every letter matches, so the answer is 0.
- No letters in common. "abc" to "xyz" takes 3 replacements, not 6 deletions and insertions.
Common mistakes
- Making the table m × n instead of (m + 1) × (n + 1), so there is no row or column for the empty prefix.
- Adding 1 even when the last letters match.
- Mixing up
word1[i]andword1[i − 1]: row i stands for the first i letters, so its last letter is at i − 1.
How to talk through it
- 1Clarify. Do all three edits cost the same? Can either word be empty?
- 2Find the subproblem. Look at the last letters of two prefixes; there are only three ways the last edit can go.
- 3Add a memo. The recursion repeats prefix pairs; store each one, O(m·n).
- 4Turn it into a table. Fill row 0 and column 0, then each cell from up, left and diagonal.
- 5Test out loud. Run an empty word, two equal words and Example 1 on a 4 × 4 table.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?