72. Edit Distance - Detailed Explanation
Problem statement
Description:
Given two strings, word1 and word2, return the minimum number of operations required to convert word1 into word2. You have the following three operations permitted on a word:
- Insert a character.
- Delete a character.
- Replace a character.
Examples:
-
Example 1:
- Input:
word1 = "horse",word2 = "ros". - Output:
3. - Explanation: One way to convert "horse" to "ros" is:
- "horse" → "rorse" (replace 'h' with 'r').
- "rorse" → "rose" (remove the first 'r').
- "rose" → "ros" (remove the 'e').
- Input:
-
Example 2:
- Input:
word1 = "intention",word2 = "execution". - Output:
5. - Explanation: One way to convert "intention" to "execution" is:
- "intention" → "inention" (remove 't').
- "inention" → "enention" (replace 'i' with 'e').
- "enention" → "exention" (replace 'n' with 'x').
- "exention" → "exection" (replace 'n' with 'c').
- "exection" → "execution" (insert 'u').
- Input:
Constraints:
- The lengths of the strings can vary, commonly up to 500 characters in many test cases.
- Both strings can be empty.
The minimum number of operations between two strings is called the edit distance, or the Levenshtein distance. This question is an instance of multidimensional dynamic programming. Grokking Dynamic Programming teaches it in the Longest Common Substring chapter. Every cell of a table holds the best answer for one pair of prefixes, and the value of a cell is the cheapest of a small set of earlier cells. Edit Distance is also one of the dynamic programming entries on the Blind 75 list, so it is worth being able to write it from memory.
Hints before the solution
-
Dynamic programming insight: Think about solving the problem for smaller prefixes of the strings. Once you can compute the minimum edit distance for prefixes of
word1andword2, those results build up the answer for the full strings. -
Base cases are key: Consider what happens when one of the strings is empty. Converting an empty string to a non-empty string, or the reverse, requires inserting or deleting every character.
-
Subproblem relationship: If the last characters of the two strings match, the edit distance for the full strings equals the distance for the prefixes without those last characters. If they differ, consider all three operations and take the cheapest.
Approaches
Approach: dynamic programming (bottom-up)
Idea:
- Define
dp[i][j]as the minimum edit distance between the firsticharacters ofword1and the firstjcharacters ofword2. - Base cases:
dp[0][j] = j, since turning an empty string into a string of lengthjrequiresjinsertions.dp[i][0] = i, since turning a string of lengthiinto an empty string requiresideletions.
- Recurrence relation:
- If the characters match, meaning
word1[i-1] == word2[j-1], thendp[i][j] = dp[i-1][j-1]and the operation count does not rise. - Otherwise, consider three moves and take the minimum:
- Insert:
dp[i][j-1] + 1. - Delete:
dp[i-1][j] + 1. - Replace:
dp[i-1][j-1] + 1.
- Insert:
- In one line, that is
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 1).
- If the characters match, meaning
Why it works:
- The table builds the answer from solutions to smaller subproblems, and each cell is computed only once.
- Once the
dptable is complete,dp[m][n]holds the answer, wheremis the length ofword1andnis the length ofword2.
Design Gurus teaches this problem in the Edit Distance lesson of Grokking Dynamic Programming, next to the other questions that fill a table over two strings.
Code implementations
Python implementation
Java implementation
Complexity analysis
-
Time complexity:
- The solution fills a table of size
(m+1) x (n+1)with a nested loop, which gives a time complexity of O(m * n).
- The solution fills a table of size
-
Space complexity:
- The DP table uses O(m * n) space.
- Space optimization can reduce that to O(min(m, n)) if needed, since each row depends only on the row above it.
Step-by-step walkthrough with a visual example
Consider converting word1 = "horse" to word2 = "ros":
-
Initialization:
- Create a DP table
dpwith dimensions6 x 4, since "horse" has 5 characters and "ros" has 3. - Set
dp[0][j] = jforjfrom 0 to 3. - Set
dp[i][0] = iforifrom 0 to 5.
- Create a DP table
-
Filling the table:
- For each
ifrom 1 to 5 and eachjfrom 1 to 3, computedp[i][j]. - Compare
word1[i-1]withword2[j-1]. - If they are equal,
dp[i][j] = dp[i-1][j-1]. - If they differ,
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 1).
- For each
-
Final answer:
- After the table is complete, the answer sits in
dp[5][3], which is3for this input.
- After the table is complete, the answer sits in
Common mistakes
-
Incorrect base case initialization: Leaving the first row and the first column unset, or filling them with zeros, produces wrong answers everywhere downstream.
-
Off-by-one errors: Be careful with array indices. The table is one row and one column larger than the string lengths, so that the empty prefix has a row and a column of its own.
-
Ignoring equal characters: Failing to test whether the two characters match adds an operation that is not needed, which overestimates the edit distance.
Edge cases
-
One or both strings empty:
- If
word1is empty, the answer is the length ofword2, all insertions. - If
word2is empty, the answer is the length ofword1, all deletions.
- If
-
Identical strings: The edit distance is
0, since the diagonal of matches carries every cell forward without a cost.
Alternative variations and related problems
-
Alternative variation: Some questions ask for the actual sequence of operations rather than the count. Answering that means walking backward through the DP table from
dp[m][n]and recording which predecessor cell produced each value. -
Unique Paths: The Unique Paths answer uses the same two-dimensional table shape, but it adds counts instead of taking a minimum, which is a clean way to see what the table structure does and does not decide.
-
Related problems for further practice:
- Longest Common Subsequence, the closest relative, since a match on the diagonal plays the same role there.
- Longest Common Substring, where a mismatch resets the run to zero instead of paying for an operation.
- Minimum Insertions and Deletions to Transform a String, which is edit distance without the replace move.
- Sequence Alignment Problems, the same recurrence with per-operation costs that are not all 1.
For the wider map of techniques these questions draw on, the article on the recurring LeetCode patterns sorts dynamic programming into the handful of shapes that keep returning in interviews.

GET YOUR FREE
Coding Questions Catalog

$99

$197

$72