Edit Distance (LeetCode 72): Solution and Explanation
Given two words, find the minimum number of single-character operations needed to turn the first into the second. Each operation inserts one character, deletes one character, or replaces one character with another.
Watch it run step by step
Try your own input and write the code →Intuition
Start by thinking about the last characters of both words. If they match, they cost nothing, and the answer is the edit distance between the two words with that last character removed. If they differ, the final operation must be one of three things: delete the last character of word1, insert the last character of word2 at the end of word1, or replace one with the other. Each choice costs 1 and leaves a smaller version of the same problem.
Written as plain recursion, that is a branching factor of three and roughly 3^(m + n) calls, because the same pair of prefixes gets reached through many different sequences of edits. That repetition is the signal for dynamic programming. There are only (m + 1) × (n + 1) distinct pairs of prefixes, so you can solve each once and store it.
Let dp[i][j] be the edit distance between the first i characters of word1 and the first j of word2. Turning a prefix into the empty string takes i deletions, and building a prefix from nothing takes j insertions, which fills the first column and row. Every other cell is either its diagonal neighbor (on a match) or one plus the minimum of the cell above (delete), to the left (insert), and diagonal (replace). The bottom-right cell is the answer.
Approach: 2D bottom-up dynamic programming
- Let
mandnbe the word lengths and allocate an (m + 1) by (n + 1) table of zeros. - Fill
dp[i][0] = ifor every row anddp[0][j] = jfor every column. These are the costs of converting to or from an empty string. - Loop
ifrom 1 tomandjfrom 1 ton. - If
word1[i-1] == word2[j-1], copy the diagonal:dp[i][j] = dp[i-1][j-1]. - Otherwise set
dp[i][j]to 1 plus the minimum ofdp[i-1][j](delete),dp[i][j-1](insert) anddp[i-1][j-1](replace). - Return
dp[m][n].
Step-by-step example
word1 = "horse", word2 = "ros"
- The first row is [0, 1, 2, 3] and the first column runs 0 through 5.
- Row 'h' has no matches and becomes [1, 1, 2, 3]. Row 'o' matches the 'o' of 'ros' at column 2, copying the diagonal value 1, and becomes [2, 2, 1, 2].
- Row 'r' matches at column 1, copying
dp[2][0] = 2, and becomes [3, 2, 2, 2]. - Row 's' matches at column 3, copying
dp[3][2] = 2, and becomes [4, 3, 3, 2]. - Row 'e' has no match. Its last cell is 1 + min(2, 4, 3) = 3, so the answer is 3: replace 'h' with 'r', delete 'r', delete 'e'.
Code: Python, Java, C++
1class Solution:
2 def minDistance(self, word1: str, word2: str) -> int:
3 m, n = len(word1), len(word2)
4 dp = [[0] * (n + 1) for _ in range(m + 1)]
5
6 # Base cases
7 for i in range(m + 1):
8 dp[i][0] = i
9 for j in range(n + 1):
10 dp[0][j] = j
11
12 # Fill DP table
13 for i in range(1, m + 1):
14 for j in range(1, n + 1):
15 if word1[i-1] == word2[j-1]:
16 dp[i][j] = dp[i-1][j-1]
17 else:
18 dp[i][j] = 1 + min(
19 dp[i-1][j], # delete
20 dp[i][j-1], # insert
21 dp[i-1][j-1] # replace
22 )
23
24 return dp[m][n]1class Solution {
2 public int minDistance(String word1, String word2) {
3 int m = word1.length(), n = word2.length();
4 int[][] dp = new int[m + 1][n + 1];
5
6 for (int i = 0; i <= m; i++) dp[i][0] = i;
7 for (int j = 0; j <= n; j++) dp[0][j] = j;
8
9 for (int i = 1; i <= m; i++) {
10 for (int j = 1; j <= n; j++) {
11 if (word1.charAt(i-1) == word2.charAt(j-1)) {
12 dp[i][j] = dp[i-1][j-1];
13 } else {
14 dp[i][j] = 1 + Math.min(dp[i-1][j], Math.min(dp[i][j-1], dp[i-1][j-1]));
15 }
16 }
17 }
18 return dp[m][n];
19 }
20}1class Solution {
2public:
3 int minDistance(string word1, string word2) {
4 int m = word1.size(), n = word2.size();
5 vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
6
7 for (int i = 0; i <= m; i++) dp[i][0] = i;
8 for (int j = 0; j <= n; j++) dp[0][j] = j;
9
10 for (int i = 1; i <= m; i++) {
11 for (int j = 1; j <= n; j++) {
12 if (word1[i-1] == word2[j-1]) {
13 dp[i][j] = dp[i-1][j-1];
14 } else {
15 dp[i][j] = 1 + min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]});
16 }
17 }
18 }
19 return dp[m][n];
20 }
21};Time and space complexity
O(m × n)
Each of the (m + 1) × (n + 1) cells is filled once with a constant amount of work: one character comparison and at most a minimum of three values.
O(m × n)
The full table is stored. Since each row depends only on the previous row, it can be cut down to O(n) if you do not need to reconstruct the edit sequence.
Other approaches
Top-down recursion with memoization (time O(m × n), space O(m × n))
Write the recurrence directly as a recursive function on (i, j) and cache the results. It is often easier to derive in an interview and only visits reachable states, but carries recursion overhead and depth up to m + n.
Rolling one-row DP (time O(m × n), space O(min(m, n)))
Keep only the previous row plus a saved diagonal value while filling the current row. It gives the same answer with much less memory, which matters when both words are long.
Common mistakes
- Indexing the strings with
iandjinstead ofi - 1andj - 1. The table is shifted by one to make room for the empty-prefix row and column. - Leaving the first row and column at zero. Without those base cases, the table claims that converting 'abc' to an empty string is free.
- Adding 1 even when the characters match. A match costs nothing, so the cell copies its diagonal value directly.
- Mixing up which neighbor means insert and which means delete. The answer is the same because you take the minimum, but reconstructing the actual edits will be wrong.
Frequently asked questions
What is the Levenshtein distance?
It is another name for this exact quantity: the minimum number of single-character insertions, deletions and substitutions to turn one string into another. It is widely used in spell checkers, fuzzy search and DNA alignment.
Why is Edit Distance solved with dynamic programming?
The best edit sequence for two words is built from the best sequences for their prefixes, and the same prefix pairs come up again and again in a naive search. Dynamic programming solves each of the (m + 1) × (n + 1) prefix pairs once instead of exponentially many times.
Can Edit Distance be done in O(n) space?
Yes. Each row only depends on the row above it, so you can keep two rows, or one row plus a temporary for the diagonal. You lose the ability to backtrack through the table to list the actual edits.
How is Edit Distance related to Longest Common Subsequence?
Both use a 2D table over prefixes with a match case that copies the diagonal. If only insertions and deletions were allowed, the edit distance would equal m + n minus twice the LCS length.