Edit distance (Levenshtein distance) powers spell checkers, DNA alignment and diff tools. It is the archetypal 2D DP: the state is a pair of prefixes and each transition is one edit.
A spell checker offers the dictionary word that is the fewest single-character edits away from what you typed. One edit inserts a character, deletes one, or replaces one character with another. Write min_distance(word1, word2) that returns the smallest number of edits that turns word1 into word2.
Examples
Input: word1 = "bread", word2 = "roads"
Output: 3
Explanation: bread -> read (delete b) -> road (replace e with o) -> roads (insert s)
Input: word1 = "garden", word2 = "danger"
Output: 4
Constraints
0 <= len(word1), len(word2) <= 500, lowercase letters only- Target: O(m * n) time
Goals
- Design a 2D DP whose transitions correspond to three different edit operations
- Handle base cases where one string is empty (all inserts or all deletes)
- Explain each cell of a DP table in words before writing the code