Open In App
Related Articles

Minimum characters to be added at front to make string palindrome

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given string str we need to tell minimum characters to be added in front of the 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.

Naive approach: Start checking the string each time if it is a palindrome and if not, then delete the last character and check again. When the string gets reduced to either a palindrome or an empty string then the number of characters deleted from the end till now will be the answer as those characters could have been inserted at the beginning of the original string in the order which will make the string a palindrome.

Below is the implementation of the above approach:

C++

// 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;
}

                    

Java

// 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

                    

Python 3

# 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

                    

C#

// 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

                    

Javascript

<script>
        // JavaScript Program to implement
        // the above approach
 
        // function for checking string is palindrome or not
        function ispalindrome(s) {
            let l = s.length;
            let j;
 
            for (let i = 0, j = l - 1; i <= j; i++, j--) {
                if (s[i] != s[j])
                    return false;
            }
            return true;
        }
 
        // Driver code
        let s = "BABABAA";
        let cnt = 0;
        let 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);
            }
        }
 
        // print the number of insertion at front
        if (flag)
            document.write(cnt);
 
     // This code is contributed by Potta Lokesh
 
    </script>

                    

Output
2






Time complexity: O(n2)
Auxiliary Space: O(1)
Thank you Sanny Kumar for suggesting this approach.


Efficient approach: We can solve this problem efficiently in O(n) time using lps array of KMP algorithm
First, we concat string by concatenating the 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 represents the longest proper prefix which is also a suffix. We can use this lps array to solve 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 characters needed to make the string a palindrome is the length of the input string minus the last entry of our lps array. 

Below is the implementation of the above approach:

C++

// 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;
}

                    

Java

// Java program for getting minimum character to be
// added at front to make string palindrome
import java.util.*;
class GFG
{
 
// returns vector lps for given string str
public static int[] computeLPSArray(String str)
{
    int n = str.length();
    int lps[] = new int[n];
    int i = 1, len = 0;
    lps[0] = 0; // lps[0] is always 0
     
    while (i < n)
    {
        if (str.charAt(i) == str.charAt(len))
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            // 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
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}
 
// Method returns minimum character to be added at
// front to make string palindrome
static int getMinCharToAddedToMakeStringPalin(String str)
{
    StringBuilder s = new StringBuilder();
    s.append(str);
     
    // Get concatenation of string, special character
    // and reverse string
    String rev = s.reverse().toString();
    s.reverse().append("$").append(rev);
     
    // Get LPS array of this concatenated string
    int lps[] = computeLPSArray(s.toString());
    return str.length() - lps[s.length() - 1];
}
 
// Driver Code
public static void main(String args[])
{
    String str = "AACECAAAA";
    System.out.println(getMinCharToAddedToMakeStringPalin(str));
}
}
 
// This code is contributed by Sparsh Singhal

                    

Python3

# 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] * M
 
    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

                    

C#

// C# program for getting minimum character to be 
// added at front to make string palindrome 
using System;
using System.Text;
 
public class GFG{
 
  // returns vector lps for given string str 
  public static int[] computeLPSArray(string str)
  {
    int n = str.Length;
    int[] lps = new int[n];
    int i = 1, len = 0;
    lps[0] = 0; // lps[0] is always 0 
 
    while (i < n) 
    {
      if (str[i] == str[len])
      {
        len++;
        lps[i] = len;
        i++;
      }
      else
      {
        // 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
        {
          lps[i] = 0;
          i++;
        }
      }
    }
    return lps;
  }
 
  // Method returns minimum character to be added at 
  // front to make string palindrome 
  static int getMinCharToAddedToMakeStringPalin(string str) 
  
    char[] s = str.ToCharArray();
 
    // Get concatenation of string, special character 
    // and reverse string 
    Array.Reverse( s );
    string rev = new string(s);
 
    string concat=  str + "$" + rev;
 
    // Get LPS array of this concatenated string
    int[] lps = computeLPSArray(concat);
    return str.Length - lps[concat.Length - 1];
  }
   
  // Driver Code
  static public void Main (){
    string str = "AACECAAAA"
    Console.WriteLine(getMinCharToAddedToMakeStringPalin(str));
  }
}
 
// This code is contributed by avanitrachhadiya2155

                    

Javascript

<script>
 
// JavaScript program for getting minimum character to be
// added at front to make string palindrome
 
// returns vector lps for given string str
function computeLPSArray(str)
{
    let M = str.length;
    let lps = new Array(M);
 
    let len = 0;
    lps[0] = 0; // lps[0] is always 0
 
    // the loop calculates lps[i] for i = 1 to M-1
    let 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
function getMinCharToAddedToMakeStringPalin(str)
{
    let revStr = str.split('').reverse().join('');
 
    // Get concatenation of string, special character
    // and reverse string
    let concat = str + "$" + revStr;
 
    // Get LPS array of this concatenated string
    let lps = computeLPSArray(concat);
 
    // By subtracting last entry of lps vector from
    // string length, we will get our result
    return (str.length - lps[lps.length-1]);
}
 
// Driver program to test above functions
let str = "AACECAAAA";
document.write(getMinCharToAddedToMakeStringPalin(str));
 
// This code is contributed by shinjanpatra
 
</script>

                    

Output
2






Time Complexity: O(n)
Auxiliary Space: O(n)

Another approach using “Two Pointers”:-

  • Initialize two pointers start and end to the beginning and end of the string, respectively.
  • While start is less than end, if the characters at the start and end pointers are equal, move the start pointer one position to the right and the end pointer one position to the left. If the characters are not equal, increment the res variable (which keeps track of the number of characters that need to be added) and reset the start and end pointers to the beginning and end of the string with a reduced number of characters.
  • When start is no longer less than end, return the value of res as the minimum number of characters that need to be added to the front of the string to make it a palindrome.

Here’s the code for above approach:

C++

#include <iostream>
#include <string>
 
using namespace std;
 
class Solution {
public:
    int addMinChar(string str1) {
        int n = str1.length();
        int start = 0;
        int end = n - 1;
        int res = 0;
        while (start < end) {  // While the pointers have not met in the middle of the string
            if (str1[start] == str1[end]) {  // If the characters at the start and end pointers are equal
                start++;  // Move the start pointer to the right
                end--;  // Move the end pointer to the left
            }
            else {
                res++;  // Increment the count of characters to be added
                start = 0;  // Reset the start pointer to the beginning of the string
                end = n - res - 1;  // Reset the end pointer to the end of the string with a reduced number of characters
            }
        }
        return res;  // Return the count of characters to be added
    }
};
 
int main() {
    Solution sol;
    string str = "AACECAAAA";
    cout << sol.addMinChar(str) << endl;
    return 0;
}

                    

Java

class Solution {
    public int addMinChar(String str1) {
        int n = str1.length();
        int start = 0;
        int end = n - 1;
        int res = 0;
        while (start < end) {  // While the pointers have not met in the middle of the string
            if (str1.charAt(start) == str1.charAt(end)) {  // If the characters at the start and end pointers are equal
                start++;  // Move the start pointer to the right
                end--;  // Move the end pointer to the left
            }
            else {
                res++;  // Increment the count of characters to be added
                start = 0// Reset the start pointer to the beginning of the string
                end = n - res - 1// Reset the end pointer to the end of the string with a reduced number of characters
            }
        }
        return res;  // Return the count of characters to be added
    }
}
 
class Main {
    public static void main(String[] args) {
        Solution sol = new Solution();
        String str = "AACECAAAA";
        System.out.println(sol.addMinChar(str));
    }
}

                    

Python3

class Solution:
    def addMinChar(self, str1):
        n = len(str1)
        start = 0
        end = n - 1
        res = 0
        while start < end:  # While the pointers have not met in the middle of the string
            if str1[start] == str1[end]:  # If the characters at the start and end pointers are equal
                start += 1  # Move the start pointer to the right
                end -= 1  # Move the end pointer to the left
            else:
                res += 1  # Increment the count of characters to be added
                start = 0  # Reset the start pointer to the beginning of the string
                end = n - res - 1  # Reset the end pointer to the end of the string with a reduced number of characters
        return res  # Return the count of characters to be added
 
if __name__ == "__main__":
    string = "AACECAAAA"
    print(addMinChar(string))

                    

C#

using System;
 
public class Solution {
    public int AddMinChar(string str1) {
        int n = str1.Length;
        int start = 0;
        int end = n - 1;
        int res = 0;
        while (start < end) {
            if (str1[start] == str1[end]) {
                start++;
                end--;
            } else {
                res++;
                start = 0;
                end = n - res - 1;
            }
        }
        return res;
    }
}
 
public class Program {
    public static void Main() {
        string s = "AACECAAAA";
        Solution solution = new Solution();
        int result = solution.AddMinChar(s);
        Console.WriteLine(result);
    }
}

                    

Javascript

class Solution {
    addMinChar(str1) {
        let n = str1.length;
        let start = 0;
        let end = n - 1;
        let res = 0;
        while (start < end) {
            if (str1[start] === str1[end]) {
                start++;
                end--;
            } else {
                res++;
                start = 0;
                end = n - res - 1;
            }
        }
        return res;
    }
}
 
let s = "AACECAAAA";
let solution = new Solution();
let result = solution.addMinChar(s);
console.log(result);

                    

Output
2






The time complexity of this algorithm is O(n), where n is the length of the input string. 
The space complexity is O(1), since the algorithm uses only constant extra space.

Another Approach: Similar to KMP algorithm, we have Z-Algorithm. It can solve this problem efficiently in O(n) time using Z array of Z algorithm
First, we concat string by concatenating the given string, a special character and reverse of given string then we will get Z array for this concatenated string, recall that each index of Z array represents the length of the longest substring starting at index i, which is also a proper prefix. We can use this Z array to solve the problem. 
 

For string = AACECAAAA
Concatenated String = AACECAAAA$AAAACECAA
Z array will be {0, 1, 0, 0, 0, 2, 2, 2, 1, 0, 2, 2, 7, 1, 0, 0, 0, 2, 1}


After calculating the Z array, we will traverse the Z array, now, we are only interested in the values in which the Z[i] is equal to the length of the substring starting from i and ending at the concat.size() – 1, this works because this substring will also be a suffix. Finally minimum number of characters needed to make the string a palindrome is the length of the input string mminum the maximum of the Z array, where the above condition satisifies. 

Below is the implementation of the above approach:

C++

// C++ program for getting minimum character to be
// added at front to make string palindrome
#include <bits/stdc++.h>
using namespace std;
 
// returns vector Z for given string str
vector<int> ComputeZArray(string str)
{
    // create a Z-array
    vector<int> Z(str.size(), 0);
     
    // window between [l, r] (inclusive)
    int l = 0, r = 0;
     
    // traverse the string
    for(int i = 1; i < str.size(); i++){
         
        // if i is in the range of l and r
        if(i <= r){
            // take the
            // Z value as Z[i - l], it means value of Z from it's prefix
            // Z value as the maximum range which is currently equal starting from i, i.e. r - i + 1
            // take minimum of two
            Z[i] = min(Z[i - l], r - i + 1);
        }
         
        // with naive approach check the prefix value and current value of Z
        while(str[0 + Z[i]] == str[i + Z[i]]){
            Z[i]++;
        }
         
        // update l and r, if found a better range
        if(i + Z[i] - 1 > r){
            l = i;
            r = i + Z[i] - 1;
        }
         
    }
     
    return Z;
}
 
// Method returns minimum character to be added at
// front to make string palindrome
int getMinCharToAddedToMakeStringPalin(string str) {
     
    // size of the string
    int n= str.size();
     
    // reversing the string
    string revStr = str;
    reverse(begin(revStr), end(revStr));
     
    // concating the string
    string concat = str + "$" + revStr;
     
    // count of characters to remove from the string
    int charactersToRemove = INT_MIN;
     
    // computing the Z array, using the Z-Algorithm
    vector<int> Z = ComputeZArray(concat);
     
    // Add them to the result, only if the Z value at index i
    // touches the last character of the string
    // for example:
    // str = "AABA"
    // concat = AABA$ABAA
    // Z array = 0 0 1 1 0 1 3 0 1
    // at index = 6, we had value as 3, which is also equal to the concat.size() - i, i.e. at the end.
    for(int i = 0; i < Z.size(); i++){
        if(Z[i] == concat.size() - i) charactersToRemove = max(charactersToRemove, Z[i]);
    }
 
    return n - charactersToRemove;
}
 
 
// Driver program to test above functions
int main()
{
    string str = "AACECAAAA";
    cout << getMinCharToAddedToMakeStringPalin(str);
    return 0;
}

                    

Java

import java.util.*;
 
public class GFG {
 
    // Function to compute Z-array for a given string
    public static List<Integer> computeZArray(String str)
    {
        List<Integer> Z = new ArrayList<>(
            Collections.nCopies(str.length(), 0));
        int l = 0,
            r = 0; // Pointers to maintain the window [l, r]
 
        for (int i = 1; i < str.length(); i++) {
            if (i <= r) {
                Z.set(i, Math.min(Z.get(i - l), r - i + 1));
            }
 
            // Expanding the window using Z-Algorithm
            while (i + Z.get(i) < str.length()
                   && str.charAt(Z.get(i))
                          == str.charAt(i + Z.get(i))) {
                Z.set(i, Z.get(i) + 1);
            }
 
            // Updating the window if a better range is
            // found
            if (i + Z.get(i) - 1 > r) {
                l = i;
                r = i + Z.get(i) - 1;
            }
        }
 
        return Z;
    }
 
    // Method to find the minimum character to be added at
    // the front to make the string palindrome
    public static int
    getMinCharToAddedToMakeStringPalin(String str)
    {
        int n = str.length();
 
        // Reversing the string to find the largest suffix
        // palindrome
        String revStr
            = new StringBuilder(str).reverse().toString();
 
        // Concatenating the string with "$" as a separator
        String concat = str + "$" + revStr;
 
        // Initializing the variable to store the count of
        // characters to remove
        int charactersToRemove = Integer.MIN_VALUE;
 
        // Computing the Z-array using the Z-Algorithm
        List<Integer> Z = computeZArray(concat);
 
        // Finding the maximum value of Z[i] where Z[i]
        // touches the end of the string
        for (int i = 0; i < Z.size(); i++) {
            if (Z.get(i) == concat.length() - i) {
                charactersToRemove = Math.max(
                    charactersToRemove, Z.get(i));
            }
        }
 
        return n - charactersToRemove;
    }
 
    // Driver program to test the above functions
    public static void main(String[] args)
    {
        String str = "AACECAAAA";
        System.out.println(
            getMinCharToAddedToMakeStringPalin(
                str)); // Output: 2
    }
}
 
// This code is contribute by rambabuguphka

                    

Python3

# Python3 program for getting minimum character to be
# added at front to make string palindrome
def compute_z_array(string):
    n = len(string)
    Z = [0] * n
    l = 0
    r = 0
 
    for i in range(1, n):
        if i <= r:
            # Calculate the Z value as Z[i - l].
            # It means the value of Z from its prefix.
            # The Z value is the maximum range which is
            # currently equal starting from i, i.e. r - i + 1.
            # Take the minimum of the two.
            Z[i] = min(Z[i - l], r - i + 1)
 
        # Check the prefix value and current value of Z.
        while i + Z[i] < n and string[Z[i]] == string[i + Z[i]]:
            Z[i] += 1
 
        # Update l and r if a better range is found.
        if i + Z[i] - 1 > r:
            l = i
            r = i + Z[i] - 1
 
    return Z
 
 
def get_min_char_to_make_string_palindrome(string):
    n = len(string)
    rev_str = string[::-1# Reverse the string
    concat = string + "$" + rev_str  # Concatenate the original string, a special character "$", and the reversed string
    characters_to_remove = float('-inf'# Count of characters to remove from the string
 
    # Compute the Z array using the Z-Algorithm
    Z = compute_z_array(concat)
 
    # Add them to the result if the Z value at index i touches the last character of the string.
    for i in range(len(Z)):
        if Z[i] == len(concat) - i:
            characters_to_remove = max(characters_to_remove, Z[i])
 
    return n - characters_to_remove
 
 
# Driver code
str = "AACECAAAA"
print(get_min_char_to_make_string_palindrome(str))

                    

C#

// C# program for getting minimum character to be
// added at front to make string palindrome
using System;
using System.Collections.Generic;
 
public class GFG {
    // Function to compute Z-array for a given string
    public static List<int> ComputeZArray(string str)
    {
        List<int> Z = new List<int>(new int[str.Length]);
        int l = 0,
            r = 0; // Pointers to maintain the window [l, r]
 
        for (int i = 1; i < str.Length; i++) {
            if (i <= r) {
                Z[i] = Math.Min(Z[i - l], r - i + 1);
            }
 
            // Expanding the window using Z-Algorithm
            while (i + Z[i] < str.Length
                   && str[Z[i]] == str[i + Z[i]]) {
                Z[i]++;
            }
 
            // Updating the window if a better range is
            // found
            if (i + Z[i] - 1 > r) {
                l = i;
                r = i + Z[i] - 1;
            }
        }
 
        return Z;
    }
 
    // Method to find the minimum character to be added at
    // the front to make the string palindrome
    public static int
    GetMinCharToAddedToMakeStringPalin(string str)
    {
        int n = str.Length;
 
        // Reversing the string to find the largest suffix
        // palindrome
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        string revStr = new string(charArray);
 
        // Concatenating the string with "$" as a separator
        string concat = str + "$" + revStr;
 
        // Initializing the variable to store the count of
        // characters to remove
        int charactersToRemove = int.MinValue;
 
        // Computing the Z-array using the Z-Algorithm
        List<int> Z = ComputeZArray(concat);
 
        // Finding the maximum value of Z[i] where Z[i]
        // touches the end of the string
        for (int i = 0; i < Z.Count; i++) {
            if (Z[i] == concat.Length - i) {
                charactersToRemove
                    = Math.Max(charactersToRemove, Z[i]);
            }
        }
 
        return n - charactersToRemove;
    }
 
    // Driver program to test the above functions
    public static void Main(string[] args)
    {
        string str = "AACECAAAA";
        Console.WriteLine(
            GetMinCharToAddedToMakeStringPalin(
                str)); // Output: 2
    }
}
 
// This code is contributed by Susobhan Akhuli

                    

Javascript

<script>
// JavaScript program for getting minimum character to be
// added at front to make string palindrome
 
// Function to compute the Z array for a given string
function computeZArray(str) {
    const n = str.length;
    const Z = new Array(n).fill(0);
    let l = 0;
    let r = 0;
 
    for (let i = 1; i < n; i++) {
        if (i <= r) {
            Z[i] = Math.min(Z[i - l], r - i + 1);
        }
 
        while (str[i + Z[i]] === str[Z[i]]) {
            Z[i]++;
        }
 
        if (i + Z[i] - 1 > r) {
            l = i;
            r = i + Z[i] - 1;
        }
    }
 
    return Z;
}
 
// Method to find the minimum characters to add at the front to make the string palindrome
function getMinCharToAddedToMakeStringPalin(str) {
    const n = str.length;
    const revStr = str.split('').reverse().join('');
    const concat = str + '$' + revStr;
    let charactersToRemove = Number.MIN_SAFE_INTEGER;
 
    const Z = computeZArray(concat);
 
    for (let i = 0; i < Z.length; i++) {
        if (Z[i] === concat.length - i) {
            charactersToRemove = Math.max(charactersToRemove, Z[i]);
        }
    }
 
    return n - charactersToRemove;
}
 
// Driver program to test the above functions
const str = "AACECAAAA";
document.write(getMinCharToAddedToMakeStringPalin(str));
 
// This code is contributed by Susobhan Akhuli
</script>

                    

Output
2






Time Complexity: O(n)
Auxiliary Space: O(n)




Last Updated : 09 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads