Edit Distance (LeetCode 72): Solution and Explanation

Hard
String
Dynamic Programming

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Let m and n be the word lengths and allocate an (m + 1) by (n + 1) table of zeros.
  2. Fill dp[i][0] = i for every row and dp[0][j] = j for every column. These are the costs of converting to or from an empty string.
  3. Loop i from 1 to m and j from 1 to n.
  4. If word1[i-1] == word2[j-1], copy the diagonal: dp[i][j] = dp[i-1][j-1].
  5. Otherwise set dp[i][j] to 1 plus the minimum of dp[i-1][j] (delete), dp[i][j-1] (insert) and dp[i-1][j-1] (replace).
  6. Return dp[m][n].

Step-by-step example

word1 = "horse", word2 = "ros"
  1. The first row is [0, 1, 2, 3] and the first column runs 0 through 5.
  2. 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].
  3. Row 'r' matches at column 1, copying dp[2][0] = 2, and becomes [3, 2, 2, 2].
  4. Row 's' matches at column 3, copying dp[3][2] = 2, and becomes [4, 3, 3, 2].
  5. 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]

Time and space complexity

Time

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.

Space

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 i and j instead of i - 1 and j - 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.