imashutosh51

Minimum Insertion Steps to Make a String Palindrome

Feb 27th, 2026
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. """
  2. We use two pointers (i, j) from both ends of the string and compare characters while moving toward the center.
  3. If they match, we move inward without any insertion; if they don’t match, we conceptually try inserting the left character at the right side or the right character at the left side, but instead of actually modifying the string, we simply count the insertion as +1 and recursively compute the minimum insertions needed for the remaining substring using memoization.
  4. """
  5. def fun(s,i,j,dp):
  6.     if i>=j:
  7.         return 0
  8.     if dp[i][j]!=-1:
  9.         return dp[i][j]
  10.     if s[i]==s[j]:
  11.         dp[i][j]=fun(s,i+1,j-1,dp)
  12.     elif s[i]!=s[j]:
  13.         dp[i][j]=1+min(fun(s,i+1,j,dp), fun(s,i,j-1,dp))
  14.     return dp[i][j]
  15.  
  16. class Solution:
  17.     def minInsertions(self, s: str) -> int:
  18.         dp=[[-1]*len(s) for _ in range(len(s))]
  19.         return fun(s,0,len(s)-1,dp)
  20.        
Add Comment
Please, Sign In to add comment