15% off all plans & roadmaps Use code

See plans

Edit Distance

Updated

TL;DR: Count the fewest inserts, deletes and replaces that turn one string into another. Store the answer for every pair of prefixes in a table, where each cell depends on three neighbours.

Problem

Given two strings word1 and word2, return the smallest number of operations needed to turn word1 into word2.

You may use these three operations on a word:

  • Insert one character
  • Delete one character
  • Replace one character with another

Example 1

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
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')

Constraints

  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters.

Constraints that matter

  • Each string has at most 500 characters, so a table of 501 x 501 cells (about 251,000 entries) is cheap. An O(m * n) solution runs well within limits.
  • Exponential recursion with three branches per mismatch cannot finish for lengths near 500. You need to reuse answers for repeated prefix pairs.
  • Either string can be empty, so the base cases must handle an empty word1 (answer is the length of word2) and an empty word2 (answer is the length of word1).
  • Only lowercase letters appear, so character comparison is a plain equality check with no case or encoding issues.
  • The answer never exceeds max(m, n), so it fits in a 32-bit int with no overflow worry.

View on LeetCode

Hints

Hint 1

This is a dynamic programming problem on two strings.

Hint 2

Compare the last characters of the two prefixes and try every legal move.

Solution

Intuition

This is a dynamic programming problem on two strings. Look at the ends of the two words. Whatever sequence of edits you use, the last character of word1 is either kept, replaced, deleted, or something gets inserted after it. That gives a small, fixed set of choices, and each choice leaves a smaller version of the same problem.

Picture a row of jars, one per prefix length of word2, that you refill left to right as you walk down word1. The hand you carry is diag: before you refill a jar, you copy its old contents into your hand, because the next jar still needs that value as its top-left neighbour.

Define dp[i][j] as the edit distance between the first i characters of word1 and the first j characters of word2. If the two last characters are equal, you keep them and the answer is dp[i-1][j-1]. If they differ, you pay 1 and pick the cheapest of three moves: replace (dp[i-1][j-1]), delete from word1 (dp[i-1][j]), or insert into word1 (dp[i][j-1]).

The signal that points to DP is the overlap. The same pair of prefixes shows up again and again from different parents. Cache each pair once and the exponential tree collapses into a grid with (m+1) * (n+1) cells.

The grid also has a useful shape. Every cell reads only its left, top and top-left neighbours. So you can fill it row by row, and you only need the previous row to compute the current one. That is what makes the O(n) space version possible.

Watch the pattern animation

Worked example

Input: word1 = "kitten", word2 = "sitting"
Output: 3
Explanation: Replace 'k' with 's' to get sitten. Replace 'e' with 'i' to get sittin. Insert 'g' at the end to get sitting. That is 3 operations, and no sequence with 2 operations exists, because the strings differ in length by 1 and still mismatch in at least two other places.

Approach 1: Brute force recursion

Compare the last characters of the two prefixes and try every legal move. If they match, drop both and recurse. If they differ, try replace, delete and insert, recurse on each, and take the cheapest plus 1.

The base cases are an empty prefix on either side. If word1 has no characters left, you must insert all j remaining characters of word2. If word2 has none left, you must delete all i remaining characters of word1.

Steps

  1. Define solve(i, j) as the edit distance between the first i characters of word1 and the first j characters of word2.
  2. If i is 0, return j. If j is 0, return i.
  3. If word1[i-1] equals word2[j-1], return solve(i-1, j-1).
  4. Otherwise compute solve(i-1, j) for delete, solve(i, j-1) for insert and solve(i-1, j-1) for replace.
  5. Return 1 plus the smallest of those three values.
  6. Call solve(m, n) and return the result.

Dry run

Use kitten and sitting (m = 6, n = 7). The call solve(6, 7) compares 'n' and 'g'. They differ, so it branches into solve(5, 7), solve(6, 6) and solve(5, 6).

The branch solve(6, 6) compares 'n' and 'n'. They match, so it becomes solve(5, 5), which compares 'e' and 'i'. These differ, so it branches again into solve(4, 5), solve(5, 4) and solve(4, 4).

The cheapest chain of choices is: replace k with s, replace e with i, and insert g. That chain costs 1 + 1 + 1 = 3, and every other chain costs at least 3, so the call returns 3.

Note that solve(4, 4) is reached from solve(5, 5) as a replace and again from solve(5, 4) as an insert. Nothing stores its value, so the whole subtree below it runs twice. That repeated work is the cost of this approach.

Complexity

TimeO(3^(m + n))
SpaceO(m + n)

Let m and n be the string lengths. Each mismatch makes three calls, and every call lowers i + j by at least 1, so the recursion depth is at most m + n. The tree can therefore hold up to 3^(m + n) calls, which is the upper bound on time. Only one path of calls is live at once, so the stack uses O(m + n) space.

PythonTested in our runner

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        def solve(i: int, j: int) -> int:
            if i == 0:
                return j  # insert the rest of word2
            if j == 0:
                return i  # delete the rest of word1
            if word1[i - 1] == word2[j - 1]:
                return solve(i - 1, j - 1)
            return 1 + min(
                solve(i - 1, j),      # delete
                solve(i, j - 1),      # insert
                solve(i - 1, j - 1),  # replace
            )

        return solve(len(word1), len(word2))
2D Array (Edit Distance / Levenshtein Distance) pattern infographic for Edit Distance

Solution pattern

2D Array (Edit Distance / Levenshtein Distance)

Part of Dynamic Programming (DP) Patterns

Approach 2: Bottom-up DP table2D Array (Edit Distance / Levenshtein Distance)

What's slow: the recursion solves the same pair (i, j) many times. Only (m+1) * (n+1) distinct pairs exist, yet the tree has exponentially many calls.

The insight that fixes it: store each answer the first time you compute it. Caching the recursion is called memoization. Because every cell depends only on cells with a smaller i or smaller j, you can skip recursion entirely and fill a table in order. That also removes any worry about recursion depth, which can reach 1000 frames here.

Row 0 holds the cost of building a prefix of word2 from nothing, which is j inserts. Column 0 holds the cost of erasing a prefix of word1, which is i deletes.

Steps

  1. Create a table dp with m+1 rows and n+1 columns.
  2. Set dp[i][0] = i for every row and dp[0][j] = j for every column.
  3. Loop i from 1 to m and j from 1 to n.
  4. If word1[i-1] equals word2[j-1], set dp[i][j] = dp[i-1][j-1].
  5. Otherwise set dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]).
  6. Return dp[m][n].

Dry run

For kitten and sitting the table has 7 rows and 8 columns. Row 0 is 0 1 2 3 4 5 6 7 and column 0 is 0 1 2 3 4 5 6.

Row 1 (k) fills as 1 1 2 3 4 5 6 7. The cell dp[1][1] compares 'k' and 's', which differ, so it is 1 + min(0, 1, 1) = 1.

Row 2 (i) fills as 2 2 1 2 3 4 5 6. The cell dp[2][2] compares 'i' and 'i', which match, so it copies dp[1][1] = 1.

Row 3 (t) is 3 3 2 1 2 3 4 5, row 4 (t) is 4 4 3 2 1 2 3 4, row 5 (e) is 5 5 4 3 2 2 3 4, and row 6 (n) is 6 6 5 4 3 3 2 3. The last cell dp[6][7] is 3, which is the answer.

Complexity

TimeO(m * n)
SpaceO(m * n)

Let m and n be the string lengths. The table has (m+1) * (n+1) cells, and each cell does one comparison and at most three lookups, so it costs O(1). Total time is O(m * n). The table itself stores (m+1) * (n+1) integers, which is the space bound.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        # dp[i][j] = edit distance between word1[:i] and word2[:j]
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(m + 1):
            dp[i][0] = i  # delete i characters
        for j in range(n + 1):
            dp[0][j] = j  # insert j characters

        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if word1[i - 1] == word2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    dp[i][j] = 1 + min(
                        dp[i - 1][j],      # delete
                        dp[i][j - 1],      # insert
                        dp[i - 1][j - 1],  # replace
                    )
        return dp[m][n]

Approach 3: Single-row DPOptimal

What's slow: the full table keeps m+1 rows, but row i reads only row i-1 and itself. Older rows are dead weight.

The insight that fixes it: keep one array of n+1 values. When you overwrite dp[j], its old value was dp[i-1][j] (the top neighbour). The left neighbour dp[j-1] is already the new row's value. The only value you lose is the top-left diagonal, so save it in a variable before you overwrite.

Edit distance is symmetric, so swap the words when word2 is longer. The row then has length min(m, n) + 1.

Why it is correct. When dp[j] is overwritten, its old value has already been saved as the top neighbour for the current cell. The variable diag holds dp[i-1][j-1], which is the value the current cell needs for its diagonal. The left neighbour dp[j-1] already holds row i, so every cell sees the same three inputs as in the full table.

Steps

  1. If word2 is longer than word1, swap them so the row length is the shorter length plus 1.
  2. Create dp of size n+1 with dp[j] = j, which is row 0.
  3. For each i from 1 to m, store diag = dp[0], then set dp[0] = i.
  4. For each j from 1 to n, save old = dp[j], which is the top neighbour.
  5. If word1[i-1] equals word2[j-1], set dp[j] = diag. Otherwise set dp[j] = 1 + min(diag, old, dp[j-1]).
  6. Set diag = old and move to the next j.
  7. After the last row, return dp[n].

Dry run

The table below shows the single array after each row of kitten (rows) against sitting (columns). Column 0 of each array is i.

Check one transition. In row 2 at j = 2, diag holds the old dp[1] = 1, and 'i' matches 'i', so dp[2] becomes 1. At j = 3, diag is the old dp[2] = 2, old is 3, and dp[2] is now 1. 'i' and 't' differ, so dp[3] = 1 + min(2, 3, 1) = 2.

Complexity

TimeO(m * n)
SpaceO(min(m, n))

The loops still visit every pair (i, j) once, and each visit does O(1) work, so time is O(m * n) with m and n the string lengths. After the swap, the array has min(m, n) + 1 entries and a few scalar variables, so extra space is O(min(m, n)). You can no longer rebuild the actual edit sequence from this array, because older rows are gone.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if len(word2) > len(word1):
            word1, word2 = word2, word1  # edit distance is symmetric
        m, n = len(word1), len(word2)
        dp = list(range(n + 1))  # row 0

        for i in range(1, m + 1):
            diag = dp[0]  # dp[i-1][0]
            dp[0] = i
            for j in range(1, n + 1):
                old = dp[j]  # dp[i-1][j]
                if word1[i - 1] == word2[j - 1]:
                    dp[j] = diag
                else:
                    dp[j] = 1 + min(diag, old, dp[j - 1])
                diag = old
        return dp[n]

Common mistakes

  • Reading word1[i] inside a loop where i is a prefix length. The table is 1-based and the string is 0-based, so compare word1[i - 1] with word2[j - 1].
  • Leaving out the 1 + in dp[i][j] = min(...) on a mismatch. Each replace, insert or delete costs one operation, so add 1 to the minimum of the three neighbours.
  • Skipping the base row and column, or filling them with 0. dp[i][0] must be i and dp[0][j] must be j, otherwise empty-string cases and the first row come out wrong.
  • Allocating an m x n table instead of (m+1) x (n+1). The extra row and column represent the empty prefix, and without them the base cases have nowhere to live.
  • Overwriting dp[j] in the single-row version before saving the old value. Save old = dp[j] first, and set diag = old after the cell is computed, or the diagonal neighbour is wrong.
  • Forgetting to reset dp[0] = i at the start of each row in the single-row version. The left edge of row i is i deletions, and a stale value corrupts the whole row.

Edge cases

  • Both strings empty: word1 = "", word2 = "" returns 0, since no operation is needed.
  • One string empty: word1 = "", word2 = "abc" returns 3 (three inserts), and the reverse also returns 3 (three deletes).
  • Identical strings such as "abc" and "abc" return 0, because every cell on the diagonal copies from its predecessor.
  • No shared characters: "abc" and "xyz" return 3, using three replaces.
  • One string is a subsequence of the other: "ace" and "abcde" return 2, using two inserts.
  • Maximum size: two 500-character strings fill about 251,000 cells. The DP finishes instantly, while plain recursion never would.

Follow-ups interviewers ask

Can you reduce the space below O(m * n)?
Yes. Row i depends only on row i-1, so keep one array of length n+1 and a variable for the top-left diagonal. Swap the strings so the array is the shorter length. Time stays O(m * n) and space becomes O(min(m, n)).
How would you print the actual sequence of edits, not only the count?
Keep the full table. Start at dp[m][n] and walk back to dp[0][0]. If the characters match, move diagonally with no edit. Otherwise move to the neighbour whose value is one less: top means delete, left means insert, diagonal means replace. Reverse the collected edits at the end. This needs the O(m * n) table, so the single-row version cannot do it directly.
What if replace costs 2, or each operation has its own cost?
The recurrence keeps its shape. Replace the 1 + on each branch with that operation's cost, for example dp[i-1][j] + deleteCost. With replace costing 2, a replace is never better than a delete plus an insert, and the problem becomes finding the longest common subsequence. In general the answer is still correct as long as all costs are non-negative.

Edit Distance FAQ

What is the time complexity of Edit Distance?

The DP solution runs in O(m * n), where m and n are the string lengths, because it fills (m+1) * (n+1) cells at constant cost each. The plain recursion is exponential, up to O(3^(m + n)).

Why use dynamic programming for Edit Distance?

The best answer for two prefixes depends on the best answers for slightly shorter prefixes, and the same prefix pairs repeat many times. DP stores each pair once, which turns an exponential search into a quadratic table fill.

Can Edit Distance be solved in O(1) extra space?

Not with the standard method. Each cell needs its left, top and top-left neighbours, so you need at least one row of about min(m, n) values. You can cut space to O(min(m, n)), but no known simple DP gets to constant space for the general problem.

What is the difference between Edit Distance and Levenshtein distance?

They are the same thing. Levenshtein distance is the usual name for the minimum number of single-character inserts, deletes and replaces needed to turn one string into another, and LeetCode 72 asks for exactly that.

Should I use memoization or a bottom-up table for Edit Distance?

Both are O(m * n). Memoization is quicker to write from the recursion, but depth can reach about 1000 calls, which is a problem in Python without raising the recursion limit. The bottom-up table has no recursion and is the safer choice.

Why does a matching last character not need any operation?

If the last characters are equal, an optimal edit script can leave them paired, so the cost is dp[i-1][j-1]. Using a delete, insert or replace there would never be cheaper than keeping the match, since dp values change by at most 1 between neighbours.

Asked at

See which companies ask this — Pro

Practise it