Edit Distance – Solution & Complexity
1. Define the Subproblem
- Let
dp[i][j]be the minimum edits needed to convert the firsticharacters ofword1into the firstjcharacters ofword2. - Empty prefixes give the base cases: converting to or from an empty string requires only insertions or deletions.
- The final answer is the value for the full lengths of both words.
2. Choose Between the Three Operations
- If the current characters match, no new edit is needed and we reuse the diagonal subproblem.
- Otherwise, try the cheapest of insert, delete, or replace.
- Each operation costs one edit plus the best smaller subproblem.
3. Optimize Space with One Row
- The recurrence only needs the previous row and the current row.
- Store distances for converting the processed prefix of
word1to every prefix ofword2. - For each character in
word1, build a freshcurrentrow fromprevious.
4. Fill Rows Left to Right
current[j - 1]represents insertion, because the target prefix is one character shorter.previous[j]represents deletion, because the source prefix is one character shorter.previous[j - 1]represents replacement or a character match.
5. Final Complete Solution
- This dynamic programming solution handles empty strings through the initialized base row and first column.
- It keeps only one previous row, so memory is linear in the length of
word2. - Time complexity is O(mn), and extra space complexity is O(n).