Coding Interview PatternsEdit Distance
MediumDynamic Programming
Edit Distance
Explanation & Solution
Description
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
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Constraints
0 <= word1.length, word2.length <= 500word1andword2consist of lowercase English letters
Approach
Dynamic Programming pattern
1. Define the DP Table
- Create a 2D array
dpof size(m+1) x (n+1)wherem = word1.lengthandn = word2.length dp[i][j]represents the minimum edit distance betweenword1[0..i-1]andword2[0..j-1]
2. Set Up Base Cases
dp[i][0] = i: converting a string of lengthito an empty string requiresideletionsdp[0][j] = j: converting an empty string to a string of lengthjrequiresjinsertions
3. Fill the Table Row by Row
- For each pair of characters
word1[i-1]andword2[j-1]: - If they match:
dp[i][j] = dp[i-1][j-1](no operation needed) - If they differ: take the minimum of three operations plus 1:
dp[i-1][j]+ 1: delete from word1dp[i][j-1]+ 1: insert into word1dp[i-1][j-1]+ 1: replace in word1
4. Return the Result
dp[m][n]contains the minimum number of operations to convert the fullword1intoword2
Key Insight
- Each cell depends on at most three neighbors: left, top, and top-left diagonal
- The recurrence captures all three edit operations elegantly in one formula
Time
O(m * n) where m and n are the lengths of the two stringsSpace
O(m * n) for the DP table (can be optimized to O(min(m, n)) with rolling arrays)