The Runtime Theory
mediumleetcode#dynamic-programming#string

Edit Distance

Compute the minimum number of insert, delete, and replace operations between two strings with dynamic programming — O(m·n).

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

inword1=horse, word2=ros

out3

inword1=intention, word2=execution

out5

inword1=a, word2=a

out0

Given two strings, return the minimum number of operations — insert a character, delete a character, or replace a character — needed to convert one into the other. This is the Levenshtein distance, and the machine must decide a sequence of edits without enumerating them.

The key insight: the problem has optimal substructure. Define dp[i][j] as the edit distance between the first i characters of word1 and the first j characters of word2. If the current characters match, the distance carries over diagonally. If not, the machine takes the cheapest of three moves: delete (up), insert (left), or replace (diagonal), each costing one operation.

Approach:

  1. Initialize the first row and column — converting to/from an empty string costs its length.
  2. Fill the table by comparing prefixes.
  3. The answer is the bottom-right cell.
python
def min_distance(word1, word2):
    m, n = len(word1), len(word2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = i
    for j in range(n + 1):
        dp[0][j] = j
    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], dp[i][j - 1], dp[i - 1][j - 1])
    return dp[m][n]

Time: O(m·n). Space: O(m·n), reducible to O(n) with two rolling rows.

Trickiest edge case: the base row and column — forgetting that the empty string is a valid prefix makes "a""" compute 0 instead of 1.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.