Form a palindrome | Practice | GeeksforGeeks

Given a string, find the minimum number of characters to be inserted to convert it to palindrome.
For Example:
ab: Number of insertions required is 1. bab or aba
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd

Example 1:
Input: str = "abcd"
Output: 3
Explanation: Inserted character marked
with bold characters in dcbabcd

Example 2:
Input: str = "aa"
Output: 0
Explanation:"aa" is already a palindrome.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function countMin() which takes the string str as inputs and returns the answer.

Expected Time Complexity: O(N2), N = |str|
Expected Auxiliary Space: O(N2)

Constraints:
1 ≤ |str| ≤ 103
str contains only lower case alphabets.
0
chessnoobdjin 8 hours
C++
int findMinInsertions(string S){
    int n = S.size(), dp[n+1][n+1];
    memset(dp, 0, sizeof(dp));
    string s = S;
    reverse(s.begin(), s.end());
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++){
            if(s[i-1] == S[j-1])
                dp[i][j] += 1+dp[i-1][j-1];
            else
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
        }
    }
    return n-dp[n][n];
}
+1
akkeshri140420011 day ago
int lps(vector<vector<int>>&dp,int n,string &str){
     for(int g=0;g<n;g++){
        for(int i=0,j=g;j<n;j++,i++){
            if(g==0){
                dp[i][j]=1;
            }
            else if(g==1){
                if(str[i]==str[j]){
                    dp[i][j]=2;
                }
                else{
                    dp[i][j]=1;
                }
            }
            else{
                if(str[i]==str[j]){
                    dp[i][j]=2+dp[i+1][j-1];
                }
                else{
                    dp[i][j]=max(dp[i][j-1],dp[i+1][j]);
                }
            }
        }
    }
    return dp[0][n-1];
 }
   int countMin(string str){
   //complete the function here
    int n=str.length();
    vector<vector<int>>dp(n,vector<int>(n));
    return n-lps(dp,n,str);
   }

0
himanshukug19cs2 days ago
   int[][] dp;   int sol(String str,int i ,int j){        if(i>=j)           return 0;           if(dp[i][j]!=-1)               return dp[i][j];       if(str.charAt(i)==str.charAt(j))            return dp[i][j]=sol(str,i+1,j-1);       else           return dp[i][j]=1+Math.min(sol(str,i+1,j),sol(str,i,j-1));   }    int countMin(String str)   {       // code here   dp= new int[str.length()][str.length()];          for(int i=0;i<str.length();i++){          Arrays.fill(dp[i],-1);      }      return sol(str,0,str.length()-1);   }
0
2019sushilkumarkori5 days ago
int countMin(string str){
    //complete the function here
        int n = str.length();
        string str2 = str;
        reverse(str2.begin(),str2.end());
        int t[n+1][n+1];
        for(int i=0;i<=n;i++){
            for(int j=0;j<=n;j++){
                if(i==0 || j==0){
                    t[i][j] = 0;
                }
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                if(str[i-1]==str2[j-1]){
                    t[i][j] = 1+t[i-1][j-1];
                }
                else{
                    t[i][j] = max(t[i][j-1],t[i-1][j]);
                }
            }
        }
        return n-t[n][n];
    }
0
taakiyabhicu
This comment was deleted.
+1
1107khyati2 weeks ago
n-LPS(str) and to find LPS = LCS(str, reverse of str)
class Solution{
  public:
    
    int LCS(string str,string s)
    {
        int n=str.length();
        int m=s.length();
        int maxi=INT_MIN;
        vector<vector<int>>dp(n+1,vector<int>(m+1,0));
        
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(str[i-1]==s[j-1])
                {
                    dp[i][j]=1+dp[i-1][j-1];
                    maxi=max(maxi,dp[i][j]);
                }
                else
                dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
            }
        }
        if(maxi==INT_MIN)
        return 0;
        else
        return maxi;
    }
        
    int countMin(string str)
    {
        int n=str.length();
        string s=str;
        reverse(s.begin(),s.end());
        return n-LCS(str,s);
    }
};
+1
mbi20210122 weeks ago
class Solution{ public:   int cm(string &str, string &t, vector<vector<int>>&dp, int i, int j)   {       if(i<0 || j<0)return 0;              if(dp[i][j]!=-1)return dp[i][j];       int ta=0,nt=0;       if(str[i]==t[j])       {           ta= 1+cm(str,t,dp,i-1,j-1);       }       nt= max( cm(str,t,dp,i-1,j), cm(str,t,dp,i,j-1) );       return dp[i][j]= max(ta,nt);   }    int countMin(string str){   int flag=0;   int n=str.size();   vector<vector<int>>dp(n, vector<int>(n,-1));   string t=str;   reverse(t.begin(), t.end());   int ans= cm(str, t, dp, n-1,n-1);   ans=n-ans;   return ans;         }};
0
shivaraj52 weeks ago
//Simple LCS
int countMin(string s1){   //complete the function here       string s2=s1;       reverse(s2.begin(),s2.end());       int n=s1.length();    int m=s2.length();    int dp[n+1][m+1];    for(int i=0;i<=n;i++){     for(int j=0;j<=m;j++){      if(i==0 || j==0)       dp[i][j]=0;      else if(s1[i-1]==s2[j-1])       dp[i][j]=1+dp[i-1][j-1];      else        dp[i][j]=max(dp[i-1][j],dp[i][j-1]);     }    }    //m-dp[n][m] -> insertion    return m-dp[n][m];   }
0
parasdhanwal2 weeks ago
Java | DP
 
class Solution{
    static int countMin(String a)
    {
        String b="";
        for (int i=0; i<a.length(); i++)
         {
            char ch=a.charAt(i); 
            b=ch+b; 
         }
        int x=a.length();        
        return (x-lcs(x-1,x-1,a,b));
    
    }

    static int lcs(int x, int y, String a, String b)
    {
        if(a.equals(b)){
            return a.length();
            
        }
           int dp[][]= new int [a.length()+1][b.length()+1];
           for(int i=1;i<=a.length();i++){
           for(int j=1;j<=b.length();j++){
           if(a.charAt(i-1)==b.charAt(j-1)){
            dp[i][j]=dp[i-1][j-1]+1;
        }
           else{
            dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
        }
    }
}
        
        return (dp[a.length()][b.length()]);
        }
    }
0
piyushpravanjan3332 weeks ago
DP Solution Using PYTHON (Using Concept of LCS AND LPS)
 
class Solution:   def lcs(self,Str1,Str2):       n = len(Str1)       m=len(Str2)       dp = [[-1]*(m+1) for _ in range(n+1)]       for i in range(n+1): dp[i][0] = 0       for j in range(m+1): dp[0][j] =0       for i in range(1,n+1):           for j in range(1,m+1):               if(Str1[i-1]==Str2[j-1]): dp[i][j] = 1+dp[i-1][j-1]               else:                   dp[i][j] = max(dp[i-1][j],dp[i][j-1])       return dp[n][m]          def LongPalinSeq(self,Str):       Str1= Str[::-1]       return self.lcs(Str,Str1)          def countMin(self, Str):       # code here       return len(Str) - self.LongPalinSeq(Str)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.