72. Edit Distance
Given two wordsword1andword2, 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
Thoughts:
f[i][j]: minimum number of edit distance between word1[0,...i-1] to word2[0,...j-1].
initial state:
f[i][0] = i ( need i operations(deletions) to convert word1[0, i - 1] to empty string)
f[0][j] = j (need j operations (deletions) to convert word2[0, j - 1] to empty string)
recursive state:
if word1[i-1] is equal to word2[j-1]: f[i][j] = f[i-1][j-1] (no op on current char)
else min(f[i-1][j-1] + 1 (for replacement), f[i-1][j] + 1 (for deletion of word1[i-1]), f[i][j-1] +1 (for insertion of word2[j-1] to word1[0,...i-1])
Optimization: only maintaining a row/column of the original matrix to reduce space complexity to O(n)
Code time complexity: O(n^2), space complexity: O(n^2)
Code (with optimization) time complexity: O(n^2), space complexity: O(n)
Last updated
Was this helpful?