Edit Distance
LeetCode 72 · View on LeetCode
Classic 2D DP. dp[i][j] is the minimum edits to convert word1[:i] to word2[:j]. If characters match, no edit needed; otherwise take the min of insert, delete, or replace (all +1).
def min_distance(word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if word1[i-1] == word2[j-1]:
dp[j] = prev
else:
dp[j] = 1 + min(prev, dp[j], dp[j-1])
prev = temp
return dp[n]
if __name__ == '__main__':
print(min_distance("horse", "ros")) # 3
print(min_distance("intention", "execution")) # 5
print(min_distance("", "abc")) # 3