Core Insight A table exposes how two changing prefixes or positions depend on smaller cases.
Common Pitfall Initialize the first row and column before using neighboring cells.
Description
Find minimum operations to convert one word to another.
Constraints
- Time Complexity:
O(m·n) - Space Complexity:
O(m·n)
Tags
stringdynamic-programming
Implementation Plan Translate the invariant into these small, testable moves.
- Define the row and column meaning.
- Initialize base cases.
- Fill cells in dependency order.
- Read the answer from the target cell.
def minDistance(word1, word2):
cache = [[float("inf")] * (len(word2) + 1) for i in range(len(word1) + 1)]
for j in range(len(word2) + 1):
cache[len(word1)][j] = len(word2) - j
for i in range(len(word1) + 1):
cache[i][len(word2)] = len(word1) - i
for i in range(len(word1) - 1, -1, -1):
for j in range(len(word2) - 1, -1, -1):
if word1[i] == word2[j]:
cache[i][j] = cache[i + 1][j + 1]
else:
cache[i][j] = 1 + min(
cache[i + 1][j],
cache[i][j + 1],
cache[i + 1][j + 1]
)
return cache[0][0]