Minimum characters to be added at front to make string palindrome

Given a string str we need to tell minimum characters to be added at front of string to make string palindrome.

Examples:

Input  : str = "ABC"
Output : 2
We can make above string palindrome as "CBABC"
by adding 'B' and 'C' at front.

Input  : str = "AACECAAAA";
Output : 2
We can make above string palindrome as AAAACECAAAA
by adding two A's at front of string.

A brute force way to solve this problem is to keep adding characters from last one by one at front and keep checking whether current string is palindrome or not, at max we need to check characters equal to half of length of string because in worst case half of the string need to be added at front to make string palindrome.

We can solve this problem efficiently in O(n) time using lps array of KMP algorithm.
First we concat string by concatenating given string, a special character and reverse of given string then we will get lps array for this concatenated string, recall that each index of lps array represent longest proper prefix which is also suffix. We can use this lps array for solving the problem.

For string = AACECAAAA
Concatenated String = AACECAAAA$AAAACECAA
LPS array will be {0, 1, 0, 0, 0, 1, 2, 2, 2, 
                   0, 1, 2, 2, 2, 3, 4, 5, 6, 7}

Here we are only interested in the last value of this lps array because it shows us the largest suffix of the reversed string that matches the prefix of the original string i.e these many characters already satisfy the palindrome property. Finally minimum number of character needed to make the string a palindrome is length of the input string minus last entry of our lps array. Pease see below code for better understanding

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for getting minimum character to be
// added at front to make string palindrome
#include <bits/stdc++.h>
using namespace std;
  
// returns vector lps for given string str
vector<int> computeLPSArray(string str)
{
    int M = str.length();
    vector<int> lps(M);
  
    int len = 0;
    lps[0] = 0; // lps[0] is always 0
  
    // the loop calculates lps[i] for i = 1 to M-1
    int i = 1;
    while (i < M)
    {
        if (str[i] == str[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else // (str[i] != str[len])
        {
            // This is tricky. Consider the example.
            // AAACAAAA and i = 7. The idea is similar
            // to search step.
            if (len != 0)
            {
                len = lps[len-1];
  
                // Also, note that we do not increment
                // i here
            }
            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}
  
// Method returns minimum character to be added at
// front to make string palindrome
int getMinCharToAddedToMakeStringPalin(string str)
{
    string revStr = str;
    reverse(revStr.begin(), revStr.end());
  
    // Get concatenation of string, special character
    // and reverse string
    string concat = str + "$" + revStr;
  
    //  Get LPS array of this concatenated string
    vector<int> lps = computeLPSArray(concat);
  
    // By subtracting last entry of lps vector from
    // string length, we will get our result
    return (str.length() - lps.back());
}
  
// Driver program to test above functions
int main()
{
    string str = "AACECAAAA";
    cout << getMinCharToAddedToMakeStringPalin(str);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for getting minimum 
# character to be added at the front
# to make string palindrome 
  
# Returns vector lps for given string str 
def computeLPSArray(string): 
  
    M = len(string) 
    lps = [None] *
  
    length = 0
    lps[0] = 0 # lps[0] is always 0 
  
    # the loop calculates lps[i] 
    # for i = 1 to M-1 
    i = 1
    while i < M: 
      
        if string[i] == string[length]: 
          
            length += 1
            lps[i] = length 
            i += 1
          
        else: # (str[i] != str[len]) 
          
            # This is tricky. Consider the example. 
            # AAACAAAA and i = 7. The idea is 
            # similar to search step. 
            if length != 0:
              
                length = lps[length - 1
  
                # Also, note that we do not 
                # increment i here 
              
            else: # if (len == 0) 
              
                lps[i] = 0
                i += 1
  
    return lps 
  
# Method returns minimum character 
# to be added at front to make 
# string palindrome 
def getMinCharToAddedToMakeStringPalin(string): 
  
    revStr = string[::-1]
  
    # Get concatenation of string, 
    # special character and reverse string 
    concat = string + "$" + revStr 
  
    # Get LPS array of this
    # concatenated string 
    lps = computeLPSArray(concat) 
  
    # By subtracting last entry of lps 
    # vector from string length, we
    # will get our result 
    return len(string) - lps[-1
  
# Driver Code
if __name__ == "__main__"
  
    string = "AACECAAAA"
    print(getMinCharToAddedToMakeStringPalin(string)) 
      
# This code is contributed by Rituraj Jain

chevron_right


Output:

2

Efficient Approach : Start checking the string each time if it is palindrome, and if not, then delete the last character and check again. After deleting count number of characters from the last i.e., the characters to be added to front, there will be a string which will be palindrome.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for getting minimum character to be
// added at front to make string palindrome
#include<bits/stdc++.h>
using namespace std;
  
// function for checking string is palindrome or not
bool ispalindrome(string s)
{
    int l = s.length();
    int j;
      
    for(int i = 0, j = l - 1; i <= j; i++, j--)
    {
        if(s[i] != s[j])
            return false;
    }
    return true;
}
  
// Driver code
int main()
{
    string s = "BABABAA";
    int cnt = 0;
    int flag = 0;
      
    while(s.length()>0)
    {
        // if string becomes palindrome then break
        if(ispalindrome(s))
        {
            flag = 1;
             break;
        }
        else
        {
        cnt++;
          
        // erase the last element of the string
        s.erase(s.begin() + s.length() - 1);
        }
    }
      
    // print the number of insertion at front
    if(flag)
        cout << cnt;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for getting minimum character to be
// added at front to make string palindrome
  
class GFG {
  
// function for checking string is palindrome or not 
    static boolean ispalindrome(String s) {
        int l = s.length();
  
        for (int i = 0, j = l - 1; i <= j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
  
// Driver code 
    public static void main(String[] args) {
        String s = "BABABAA";
        int cnt = 0;
        int flag = 0;
  
        while (s.length() > 0) {
            // if string becomes palindrome then break 
            if (ispalindrome(s)) {
                flag = 1;
                break;
            } else {
                cnt++;
  
                // erase the last element of the string 
                s = s.substring(0, s.length() - 1);
                //s.erase(s.begin() + s.length() - 1); 
            }
        }
  
        // print the number of insertion at front 
        if (flag == 1) {
            System.out.println(cnt);
        }
    }
  
// This code is contributed by 29AjayKumar

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program for getting minimum character
# to be added at front to make string palindrome
  
# function for checking string is 
# palindrome or not
def ispalindrome(s):
  
    l = len(s)
      
    i = 0
    j = l - 1
    while i <= j:
      
        if(s[i] != s[j]):
            return False
        i += 1
        j -= 1
      
    return True
  
# Driver code
if __name__ == "__main__":
      
    s = "BABABAA"
    cnt = 0
    flag = 0
      
    while(len(s) > 0):
      
        # if string becomes palindrome then break
        if(ispalindrome(s)):
            flag = 1
            break
          
        else:
            cnt += 1
          
            # erase the last element of the string
            s = s[:-1]
      
    # print the number of insertion at front
    if(flag):
        print(cnt)
  
# This code is contributed by ita_c

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for getting minimum character to be 
// added at front to make string palindrome 
  
using System; 
public class GFG { 
  
// function for checking string is palindrome or not 
    static bool ispalindrome(String s) { 
        int l = s.Length; 
  
        for (int i = 0, j = l - 1; i <= j; i++, j--) { 
            if (s[i] != s[j]) { 
                return false
            
        
        return true
    
  
// Driver code 
    public static void Main() { 
        String s = "BABABAA"
        int cnt = 0; 
        int flag = 0; 
  
        while (s.Length > 0) { 
            // if string becomes palindrome then break 
            if (ispalindrome(s)) { 
                flag = 1; 
                break
            } else
                cnt++; 
  
                // erase the last element of the string 
                s = s.Substring(0, s.Length - 1); 
                //s.erase(s.begin() + s.length() - 1); 
            
        
  
        // print the number of insertion at front 
        if (flag == 1) { 
            Console.WriteLine(cnt); 
        
    
  
// This code is contributed by PrinciRaj1992

chevron_right



Output:

2

Thank you Sanny Kumar for suggesting this approach.

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


6


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.