I was solving this problem at Pramp and I have trouble figuring out the algorithm for this problem. I'll paste the problem description and how I kind of solved it. It's the correct solution. It is similar to the edit distance algorithm and I used the same approach. I just wanted to see what are other ways to solve this problem.
The deletion distance of two strings is the minimum number of characters you need to delete in the two strings in order to get the same string. For instance, the deletion distance between "heat" and "hit" is 3:
By deleting 'e' and 'a' in "heat", and 'i' in "hit", we get the string "ht" in both cases. We cannot get the same string from both strings by deleting 2 letters or fewer. Given the strings str1 and str2, write an efficient function deletionDistance that returns the deletion distance between them. Explain how your function works, and analyze its time and space complexities.
input: str1 = "dog", str2 = "frog"
input: str1 = "some", str2 = "some"
input: str1 = "some", str2 = "thing"
input: str1 = "", str2 = ""
What I want to do in this solution, is to use dynamic programming in order to build a function that calculates opt(str1Len, str2Len). Notice the following: I use dynamic programming methods to calculate opt(str1Len, str2Len), i.e. the deletion distance for the two strings, by calculating opt(i,j) for all 0 ≤ i ≤ str1Len, 0 ≤ j ≤ str2Len, and saving previous values
def deletion_distance(s1, s2): m = [[0 for j in range(len(s2) +1)] for i in range(len(s1)+1)] for i in range(len(s1)+1): for j in range(len(s2)+1): if i == 0: m[i][j] = j elif j == 0: m[i][j] = i elif s1[i-1] == s2[j-1]: m[i][j] = m[i-1][j-1] else: m[i][j] = 1 + min(m[i-1][j], m[i][j-1]) return m[len(s1)][len(s2)]