Problem 53 · Dynamic Programming
Edit Distance
01Problem
Given two strings, return the minimum number of single-character inserts, deletes, or substitutions to convert one into the other.
02Key insight
dp[i][j] = cost to turn a[:i] into b[:j]; match is free, otherwise 1 + min(insert, delete, replace). Only the previous row is needed, so space drops to O(min(m,n)).
03Solution
Try it first.
TimeO(m*n)
SpaceO(min(m,n))
tests.py · 4 passing
tests.pypython4 lines
assert min_distance("horse", "ros") == 3
assert min_distance("intention", "execution") == 5
assert min_distance("", "abc") == 3
assert min_distance("same", "same") == 004Staff-level follow-up
Fuzzy search over millions of strings? Index with a BK-tree or trie + bounded Levenshtein automaton; if only distance <= k matters, use banded DP in O(k*n).