imashutosh51

Minimum Deletions to make a string palindrome

Mar 7th, 2026
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. '''
  2. LCS variation: Here you have to do some deletions to get your output so deletion must be a subsequence, it can't be substring
  3. because character might be removed from between so you must have a subsequence which is longest and it's also palindrome
  4. so what you can do is find LCS of s and reversed(s) which will be longest subsequence of s which would be also palindrome
  5. and that satisfies your requirement so total s lenght -lcs length is your answer.
  6.  
  7. '''
  8. def fun(s1,s2,n,m,dp):
  9.     if n<0 or m<0:
  10.         return 0
  11.     if dp[n][m]!=-1:
  12.         return dp[n][m]
  13.     if s1[n]==s2[m]:
  14.         dp[n][m]=1+fun(s1,s2,n-1,m-1,dp)
  15.     else:
  16.         dp[n][m]=max(fun(s1,s2,n-1,m,dp),fun(s1,s2,n,m-1,dp))
  17.     return dp[n][m]
  18.  
  19.  
  20. class Solution:
  21.     def minDeletions(self,s):
  22.         dp=[[-1]*len(s) for _ in range(len(s))]
  23.         s2=s[::-1]
  24.         lcs=fun(s,s2,len(s)-1,len(s2)-1,dp)
  25.         return len(s)-lcs
Add Comment
Please, Sign In to add comment