Edit Distance (Wagner-Fischer Algorithm)
Edit Distance
Introduction
Edit Distance (also known as Levenshtein Distance) measures how different two strings are by counting the minimum number of single-character operations needed to transform one string into the other.
The three allowed operations are:
- Insert a character
- Delete a character
- Replace a character
Video Explanation

Example
Transform "horse" → "ros":
- Replace
hwithr→rorse - Delete
r→rose - Delete
e→ros
Minimum operations: 3
Problem Definition
Given two strings word1 and word2, return the minimum number of operations to convert word1 to word2.
Dynamic Programming Approach
Define dp[i][j] as the minimum edit distance between the first i characters of word1 and the first j characters of word2.
Recurrence Relation
The three terms inside min correspond to:
dp[i-1][j]→ delete fromword1dp[i][j-1]→ insert intoword1dp[i-1][j-1]→ replace inword1
Base Cases
dp[i][0] = i— delete allicharacters ofword1dp[0][j] = j— insert alljcharacters ofword2
Visualization
For word1 = "horse", word2 = "ros":
"" r o s
"" 0 1 2 3
h 1 1 2 3
o 2 2 1 2
r 3 2 2 2
s 4 3 3 2
e 5 4 4 3
Answer: dp[5][3] = 3
Complexity
| Complexity | |
|---|---|
| Time | |
| Space | , reducible to |
where m and n are the lengths of word1 and word2.