Edit Distance - Problem
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
This problem is also known as the Levenshtein Distance.
Input & Output
Example 1 — Basic Transformation
$
Input:
word1 = "horse", word2 = "ros"
›
Output:
3
💡 Note:
horse → rorse (replace 'h' with 'r') → rose (remove 'r') → ros (remove 'e'). Total: 3 operations.
Example 2 — Insert Operations
$
Input:
word1 = "intention", word2 = "execution"
›
Output:
5
💡 Note:
intention → inention (delete 't') → enention (replace 'i' with 'e') → exention (replace first 'n' with 'x') → exection (replace 'n' with 'c') → execution (insert 'u'). Total: 5 operations.
Example 3 — Edge Case Empty String
$
Input:
word1 = "abc", word2 = ""
›
Output:
3
💡 Note:
Delete all 3 characters from 'abc' to get empty string. Total: 3 operations.
Constraints
- 0 ≤ word1.length, word2.length ≤ 500
- word1 and word2 consist of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code