Edit Distance - Problem
The Edit Distance problem asks you to find the minimum number of operations needed to transform one string into another. This is also known as the Levenshtein Distance, named after the Russian mathematician who formulated it.
You have exactly three operations at your disposal:
•
•
•
For example, to transform
1. Replace 'h' with 'r':
2. Delete 'r':
3. Delete 'e':
This gives us a minimum edit distance of 3 operations. Your goal is to find the most efficient transformation path.
You have exactly three operations at your disposal:
•
Insert a character anywhere in the string•
Delete a character from any position•
Replace a character with any other characterFor example, to transform
"horse" into "ros", you could:1. Replace 'h' with 'r':
"rorse"2. Delete 'r':
"rose"3. Delete 'e':
"ros"This gives us a minimum edit distance of 3 operations. Your goal is to find the most efficient transformation path.
Input & Output
example_1.py — Basic Transformation
$
Input:
word1 = "horse", word2 = "ros"
›
Output:
3
💡 Note:
To transform "horse" to "ros": 1) Replace 'h' with 'r' → "rorse", 2) Remove 'r' → "rose", 3) Remove 'e' → "ros". Total: 3 operations.
example_2.py — Insert Operations
$
Input:
word1 = "intention", word2 = "execution"
›
Output:
5
💡 Note:
Transform "intention" to "execution": 1) Replace 'i' with 'e', 2) Replace 'n' with 'x', 3) Replace 't' with 'e', 4) Replace 'n' with 'c', 5) Replace 'i' with 'u'. Keep "on" at the end.
example_3.py — Edge Case Empty String
$
Input:
word1 = "", word2 = "abc"
›
Output:
3
💡 Note:
To transform empty string to "abc", we need to insert 3 characters: 'a', 'b', and 'c'.
Visualization
Tap to expand
Understanding the Visualization
1
Setup the Problem
We have a misspelled word and want to find the minimum keystrokes to correct it
2
Create Decision Matrix
Build a table where each cell represents the minimum corrections needed for word prefixes
3
Fill Base Cases
First row: insertions needed, First column: deletions needed
4
Make Optimal Choices
For each position, choose the cheapest operation: insert, delete, or replace
Key Takeaway
🎯 Key Insight: Build solutions incrementally by considering all possible operations at each step and choosing the optimal path using dynamic programming.
Time & Space Complexity
Time Complexity
O(m×n)
We fill each cell in the (m+1)×(n+1) table exactly once, where m and n are string lengths
✓ Linear Growth
Space Complexity
O(m×n)
We store the entire 2D DP table of size (m+1)×(n+1)
⚡ Linearithmic Space
Constraints
- 0 ≤ word1.length, word2.length ≤ 500
- word1 and word2 consist of lowercase English letters
- Note: Empty strings are allowed as input
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code