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:
- Initialize the first row and column — converting to/from an empty string costs its length.
- Fill the table by comparing prefixes.
- The answer is the bottom-right cell.
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.