Problem
Problem page: https://leetcode.com/problems/edit-distance/
Topics: Dynamic Programming, String
Difficulty: Hard
Similar problems: (M) One Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Analysis
This is a classic dynamic programming problem. Nine times out of ten, you can improve the space complexity of a DP solution. You don't really need to allocate a whole (m+1)(n+1) matrix. The solution I'm using is down to two rows. You can cut that to one row (plus a variable to hold the value from the upper left), but you can't get it down to a 22 matrix: each cell needs the value in the same column of the previous row, so until you finish the current row, you still need to keep the remaining cells of the previous row.
Each cell in this DP matrix represents an optimal solution to the current subproblem. If each cell records which smaller subproblem's optimal solution it was built from, you can start at a given cell and follow those records back to trace the full path that makes up that cell's solution. If there's more than one optimal solution, the paths form a tree.
Row 0 and column 0 of a DP matrix usually need special handling.
For DP problems, it's also worth getting into the habit of writing out the recurrence because the formulas explain the idea more concisely:
- d[0, j] = j
- d[i, 0] = i
- d[i, j] = d[i-1, j - 1] if A[i] == B[j]
- d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1 if A[i] != B[j]
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-edit-distance/
