imashutosh51

Minimum number of deletions and insertions

Mar 7th, 2026
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. '''
  2. LCS variation:
  3. for eg s1=heap s2=pea, for reaching from s1 to s2 we need to delete h & p from s1 because h is not in s2 and p is before the 'ea'
  4. so if you observer this you will realise you are converting s1-> LCS(s1,s2) ie. 'ea' and then coverting to the s2
  5. ok, now for converting s1-> LCA, you are doing deletions of ie. len(s1)-len(LCS) chars and then again you are doing
  6. addition of len(s2)-len(LCS) characters.
  7.  
  8. so find the LCS length and deletions=len(s1)-len(LCS) and insertions=len(s2)-len(LCS) and total modificatoins=insertions+deletions
  9. '''
  10. def fun(s1,s2,n,m,dp):
  11.     if n<0 or m<0:
  12.         return 0
  13.     if dp[n][m]!=-1:
  14.         return dp[n][m]
  15.     if s1[n]==s2[m]:
  16.         dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
  17.     else:
  18.         dp[n][m]=max(fun(s1,s2,n-1,m,dp), fun(s1,s2,n,m-1,dp))
  19.     return dp[n][m]
  20.  
  21. class Solution:
  22.     def minOperations(self, s1, s2):
  23.         dp=[[-1]*len(s2) for _ in range(len(s1))]
  24.         ans=fun(s1,s2,len(s1)-1,len(s2)-1,dp)
  25.         deletions=len(s1)-ans
  26.         insertions=len(s2)-ans
  27.         return deletions+insertions
Advertisement
Add Comment
Please, Sign In to add comment