46. Edit Distance
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Example 2:
Solution: (Recursion)
Approach
If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.
Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values.
Insert: Recur for m and n-1
Remove: Recur for m-1 and n
Replace: Recur for m-1 and n-1
Time Complexity: O(3^n) exponential
Solution: (DP)
Time Complexity: O(n * m) Space Complexity: O(n * m)
Last updated