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
creepypirate2 weeks ago
sab aditya verma se hi padh ke aaye h
0
aishwaryadwani97993 weeks ago
class Solution {   static int getLCS(String x, String y, int n, int m) {       int t[][] = new int[n + 1][m + 1];       for (int i = 0; i < n + 1; i++) {           for (int j = 0; j < m + 1; j++) {               if (i == 0 || j == 0)                   t[i][j] = 0;           }       }
       for (int i = 1; i < n + 1; i++) {           for (int j = 1; j < m + 1; j++) {               if (x.charAt(i - 1) == y.charAt(j - 1))                   t[i][j] = 1 + t[i - 1][j - 1];               else                   t[i][j] = Math.max(t[i - 1][j], t[i][j - 1]);           }       }
       return t[n][m];   }
   static int getLPS(String str) {       String x = str;       String y = "";       for (int i = str.length() - 1; i >= 0; i--)           y += x.charAt(i);
       int lcs = getLCS(x, y, x.length(), y.length());       return lcs;   }
   static int countMin(String str) {       int lps = getLPS(str);       return str.length() - lps;   }}
+1
ayushkumar54511 month ago
→All credit goes to Aditya Verma :-)
int dp[1001][1001];  int plaindrome(string &a,string &b,int n,int m){      for(int i=0;i<=n;i++){          for(int j=0;j<=m;j++){              if(i==0 or j==0) dp[i][j]=0;          }      }      for(int i=1;i<n+1;i++){          for(int j=1;j<m+1;j++){              if(a[i-1]==b[j-1]){                  dp[i][j]=1+dp[i-1][j-1];              }              else{                  dp[i][j]=max(dp[i][j-1],dp[i-1][j]);              }          }      }      return dp[n][m];  }   int countMin(string str){    string b=str;    int n=str.size();    int m=b.size();    reverse(str.begin(),str.end());    int res=plaindrome(str,b,n,m);    if(str==b){        return 0;    }    else{        return (n-res);    }
+1
amonk1 month ago
my approach→
 
first calculate the lcs of the string with it's reverse.
Than check if the lcs is 0 it means every we need to insert len(string)-1 characters to make it a palindrome.
 
If the lcs is same as the length of the string than it is already a palindrome so simply return 0;
 
else return len(string)-lcs(string,reverse(string));
 
0
geminicode1 month ago
my approach in python..
def countMin(self, s):
        # code here
        
        dp = [[0 for i in range(len(s))] for j in range(len(s))]
        for g in range(len(s)):
            for i,j in zip(range(0,len(s)-g),range(g,len(s))):
                if g == 0:
                    dp[i][j] = 0
                elif g == 1:
                    if s[i] == s[j]:
                        dp[i][j] = 0
                    else:
                        dp[i][j] =1
                else:
                    if s[i] == s[j]:
                        dp[i][j] = dp[i+1][j-1]
                    else:
                        dp[i][j] = 1 + min(dp[i+1][j],dp[i][j-1])
        #print(dp)
        return dp[0][len(s)-1]
0
amansidd178612 months ago
 string rev(string s){       string ans ="";       for(int i=s.size()-1; i>=0; i--) ans+=s[i];       return ans;   }    int countMin(string A){   //complete the function here       string s2 = rev(A);       // vector<vector<int>> dp(A.size()+1,vector<int>(A.size()+1,0));       vector<int> prev(A.size()+1,0),curr(A.size()+1,0);       for(int i=0;i<=A.size();i++) prev[i]=0;              for(int i=1; i<=A.size();i++){           for(int j=1;j<=A.size();j++){               if(A[i-1]==s2[j-1]){                   curr[j] = 1 + prev[j-1];               }               else{                   curr[j] = max(prev[j],curr[j-1]);               }           }           prev = curr;       }       return A.size()-prev[A.size()];   }};
0
aryansinha18182 months ago
This is my first code submission on my own on GFG....
 
int lcs(string x, string y,int n){           int t[n+1][n+1];        for (int i = 0; i < n + 1; i++) {         for (int j = 0; j < n + 1; j++) {          if (i == 0 || j == 0) {       t[i][j] = 0;          }         }        }     for (int i = 1; i < n + 1; i++) {         for (int j = 1; j < n + 1; j++) {          if (x[i - 1] == y[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 t[n][n];       }       int countMin(string str)       {           //complete the function here           int n = str.length();           string b = str;           reverse(b.begin(),b.end());           int LCSLen  = lcs(str,b,n);           if(str == b){               return 0;           }           else {           return (str.length() - LCSLen);           }       }
0
tirtha19025682 months ago
class Solution{
   static int countMin(String str)
   {
       int n = str.length();
       StringBuilder sb = new StringBuilder(str);
       String t = sb.reverse().toString();
       return n - lcs(str,t,n,n);
   }
   
   static int lcs(String a ,String b,int m,int n){
       int[][]dp = new int[m+1][n+1];
       
       for(int i=1;i<dp.length;i++){
           for(int j=1;j<dp[0].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[m][n];
   }
   
}
0
starcode012 months ago
// → this problem is same as minimum number of deletion to //form a palindrome same code also my code is in java top-down
class Solution{   static int countMin(String str)   {       StringBuilder sb=new StringBuilder(str);         sb.reverse();       int n= str.length();       int m = sb.length();       int dp[][] = new int[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;           }       }       for(int i=1;i<n+1;i++){           for(int j=1;j<m+1;j++){               if(str.charAt(i-1)==sb.charAt(j-1))                dp[i][j] = 1+ dp[i-1][j-1];               else{                  dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);              }           }       }       return n-dp[m][n];   }}
0
amitanand22 months ago
class Solution{
  public:
int lcs(string x, string y, int n) {
int t[n+1][n+1];
	for (int i = 0; i < n + 1; i++) {
		for (int j = 0; j < n + 1; j++) {
			if (i == 0 || j == 0) {
				t[i][j] = 0;
			}
		}

	}
		for (int i = 1; i < n + 1; i++) {
		for (int j = 1; j < n + 1; j++) {
			if (x[i - 1] == y[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 t[n][n];
}
    int countMin(string str){
    //complete the function here
    string x , y;
    x = str;
    y = x;
    reverse(y.begin() , y.end());
	if (x == y) {
		return 0;
	}
	else {
	int length = lcs(x, y, x.length());
	int noOfInsertiton = x.length() - length;
	
	return noOfInsertiton;
	}

    
    }
};

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.