Edit distance
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Edit distance (Levenshtein distance) measures the minimum insertions, deletions, and substitutions to convert one string into another. We begin with plain recursion to see the 3-way branching.
Brute Force Recursion and 3-Way Branching
Edit distance is the smallest number of insertions, deletions and replacements needed to turn one string into another.
Given two words word1 and word2, what is the minimum number of single-character operations (insert, delete, replace) to turn word1 into word2?
With plain recursion, compare word1[i] and word2[j]. If characters match, no edit is needed: solve(i + 1, j + 1). If they mismatch, we try all three operations:
- Insert word2[j]: solve(i, j + 1) + 1
- Delete word1[i]: solve(i + 1, j) + 1
- Replace word1[i] with word2[j]: solve(i + 1, j + 1) + 1
Why is this slow? Because every mismatch splits into 3 recursive calls, the recursion tree branches up to 3^(m + n) times! For two 12-letter words, 3^24 is billions of calls, causing plain recursion to freeze.
Step by step
Step 1 of 8
| Row | c | u | t | |
|---|---|---|---|---|
| 0 | 1 | 2 | 3 | |
| c | 1 | 0 | 0 | 0 |
| a | 2 | 0 | 0 | 0 |
| t | 3 | 0 | 0 | 0 |
- s1
- cat
- s2
- cut
The 2D Table and the Three Cell Neighbors
Define dp[i][j] as the minimum edit distance between word1[0..i-1] and word2[0..j-1] on an (m + 1) by (n + 1) table.
If characters match (word1[i - 1] == word2[j - 1]), copy the diagonal: dp[i][j] = dp[i - 1][j - 1] with zero cost.
Example 1 · 2D Table Edit Distance
public class EditDistanceDemo { public static int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); } } } return dp[m][n]; }
public static void main(String[] args) { System.out.println("horse -> ros: " + minDistance("horse", "ros")); System.out.println("intention -> execution: " + minDistance("intention", "execution")); }}horse -> ros: 3 intention -> execution: 5
What this code does
- Transforming 'horse' into 'ros' requires 3 edits: replace 'h' with 'r', remove 'r', remove 'e'.
- Initializes boundaries with i deletions and j insertions.
- Runs in O(m * n) time and O(m * n) auxiliary space.
If characters mismatch, take 1 + min of three neighbors: dp[i][j - 1] (insert), dp[i - 1][j] (delete), or dp[i - 1][j - 1] (replace). Evaluating row by row fills the table in O(m * n) time and O(m * n) space.
Table Traversal and Step Reconstruction
To find the exact list of edits, backtrack from dp[m][n] to (0, 0).
If characters match and dp[i][j] == dp[i - 1][j - 1], move diagonally with no operation.
Example 2 · Reconstructing Edit Operations
import java.util.ArrayList;import java.util.List;
public class EditOperationsDemo { public static List<String> getOperations(String s1, String s2) { int m = s1.length(), n = s2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); } } List<String> ops = new ArrayList<>(); int i = m, j = n; while (i > 0 || j > 0) { if (i > 0 && j > 0 && s1.charAt(i - 1) == s2.charAt(j - 1)) { ops.add("Match " + s1.charAt(i - 1)); i--; j--; } else if (i > 0 && j > 0 && dp[i][j] == dp[i - 1][j - 1] + 1) { ops.add("Replace " + s1.charAt(i - 1) + " with " + s2.charAt(j - 1)); i--; j--; } else if (i > 0 && dp[i][j] == dp[i - 1][j] + 1) { ops.add("Delete " + s1.charAt(i - 1)); i--; } else { ops.add("Insert " + s2.charAt(j - 1)); j--; } } return ops; }
public static void main(String[] args) { System.out.println("Operations: " + getOperations("cat", "cut")); }}Operations: [Match t, Replace a with u, Match c]
What this code does
- Backtracks from bottom-right (m, n) to determine operation at each character.
- Identifies that 'c' and 't' match while 'a' is replaced by 'u'.
- Returns operations in reverse chronological backtracking order.
If dp[i][j] == dp[i - 1][j - 1] + 1, it was a replace. If dp[i][j] == dp[i - 1][j] + 1, it was a delete. If dp[i][j] == dp[i][j - 1] + 1, it was an insert.
Real-World Applications: Spell Checking and Fuzzy Search
Edit distance powers spelling suggestion engines, search query autocorrection, and DNA mutation distance.
In spell checking, words with edit distance <= 2 are surfaced as suggestions.
Example 3 · Space-Optimized Edit Distance
public class EditDistanceOptimizedDemo { public static int minDistanceOpt(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[] dp = new int[n + 1]; for (int j = 0; j <= n; j++) dp[j] = j; for (int i = 1; i <= m; i++) { int prevDiag = dp[0]; dp[0] = i; for (int j = 1; j <= n; j++) { int temp = dp[j]; if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[j] = prevDiag; } else { dp[j] = 1 + Math.min(prevDiag, Math.min(dp[j], dp[j - 1])); } prevDiag = temp; } } return dp[n]; }
public static void main(String[] args) { System.out.println("cat -> cut: " + minDistanceOpt("cat", "cut")); }}cat -> cut: 1
What this code does
- Uses scalar variable prevDiag to store top-left diagonal value dp[i - 1][j - 1].
- Single substitution 'a' -> 'u' transforms 'cat' into 'cut' in 1 operation.
- Reduces auxiliary memory to strictly O(n) space.
Because row i only reads row i - 1, computing distance alone requires just O(n) memory using two rolling rows.
Next step
Check your understanding
10 quick questions