Minimum number of Appends needed to make a string palindrome - GeeksforGeeks

02 Dec, 2021
Given a string s we need to tell minimum characters to be appended (insertion at the end) to make a string palindrome. 
Examples: 
Input : s = "abede"
Output : 2
We can make string palindrome as "abedeba"
by adding ba at the end of the string.

Input : s = "aabb"
Output : 2
We can make string palindrome as"aabbaa"
by adding aa at the end of the string.
The solution can be achieved by removing characters from the beginning of the string one by one and checking if the string is palindrome or not. For Example, consider the above string, s = “abede”. We check if the string is palindrome or not. The result is false, then we remove the character from the beginning of a string and now string becomes “bede”.We check if the string is palindrome or not. The result is again false, then we remove the character from the beginning of a string and now the string becomes “ede”.We check if the string is palindrome or not. The result is true, so the output becomes 2 which is the number of characters removed from the string. 
C++
Java
Python3
C#
Javascript
// C program to find minimum number of appends// needed to make a string Palindrome#include<stdio.h>#include<string.h>#include<stdbool.h> // Checking if the string is palindrome or notbool isPalindrome(char *str){    int len = strlen(str);     // single character is always palindrome    if (len == 1)        return true;     // pointing to first character    char *ptr1 = str;     // pointing to last character    char *ptr2 = str+len-1;     while (ptr2 > ptr1)    {        if (*ptr1 != *ptr2)            return false;        ptr1++;        ptr2--;    }     return true;} // Recursive function to count number of appendsint noOfAppends(char s[]){    if (isPalindrome(s))        return 0;     // Removing first character of string by    // incrementing base address pointer.    s++;     return 1 + noOfAppends(s);} // Driver program to test above functionsint main(){    char s[] = "abede";    printf("%d\n", noOfAppends(s));    return 0;}
// Java program to find minimum number of appends// needed to make a string Palindromeclass GFG{ // Checking if the string is palindrome or notstatic boolean isPalindrome(char []str){    int len = str.length;       // single character is always palindrome    if (len == 1)        return true;       // pointing to first character    int ptr1 = 0;         // pointing to last character    int  ptr2 = len-1;       while (ptr2 >= ptr1)    {        if (str[ptr1] != str[ptr2])            return false;        ptr1++;        ptr2--;    }       return true;} // Recursive function to count number of appendsstatic int noOfAppends(String s){    if (isPalindrome(s.toCharArray()))        return 0;     // Removing first character of string by    // incrementing base address pointer.    s=s.substring(1);     return 1 + noOfAppends(s);} // Driver codepublic static void main(String arr[]){    String s = "abede";    System.out.printf("%d\n", noOfAppends(s));}} // This code contributed by Rajput-Ji
# Python3 program to find minimum number of appends# needed to make a String Palindrome # Checking if the String is palindrome or notdef isPalindrome(Str):     Len = len(Str)     # single character is always palindrome    if (Len == 1):        return True     # pointing to first character    ptr1 = 0     # pointing to last character    ptr2 = Len - 1     while (ptr2 > ptr1):         if (Str[ptr1] != Str[ptr2]):            return False        ptr1 += 1        ptr2 -= 1     return True # Recursive function to count number of appendsdef noOfAppends(s):     if (isPalindrome(s)):        return 0     # Removing first character of String by    # incrementing base address pointer.    del s[0]     return 1 + noOfAppends(s) # Driver Codese = "abede"s = [i for i in se]print(noOfAppends(s)) # This code is contributed by Mohit Kumar
// C# program to find minimum number of appends// needed to make a string Palindromeusing System; class GFG{ // Checking if the string is palindrome or notstatic Boolean isPalindrome(char []str){    int len = str.Length;     // single character is always palindrome    if (len == 1)        return true;     // pointing to first character    char ptr1 = str[0];     // pointing to last character    char ptr2 = str[len-1];     while (ptr2 > ptr1)    {        if (ptr1 != ptr2)            return false;        ptr1++;        ptr2--;    }     return true;} // Recursive function to count number of appendsstatic int noOfAppends(String s){    if (isPalindrome(s.ToCharArray()))        return 0;     // Removing first character of string by    // incrementing base address pointer.    s=s.Substring(1);     return 1 + noOfAppends(s);} // Driver codepublic static void Main(String []arr){    String s = "abede";    Console.Write("{0}\n", noOfAppends(s));}} // This code has been contributed by 29AjayKumar
<script>// Javascript program to find minimum number of appends// needed to make a string Palindrome         // Checking if the string is palindrome or not    function isPalindrome(str)    {        let len = str.length;        // single character is always palindrome    if (len == 1)        return true;        // pointing to first character    let ptr1 = 0;          // pointing to last character    let  ptr2 = len-1;        while (ptr2 >= ptr1)    {        if (str[ptr1] != str[ptr2])            return false;        ptr1++;        ptr2--;    }        return true;    }         // Recursive function to count number of appends    function noOfAppends(s)    {        if (isPalindrome(s.split("")))            return 0;      // Removing first character of string by    // incrementing base address pointer.    s=s.substring(1);      return 1 + noOfAppends(s);    }         // Driver code    let s = "abede";    document.write(noOfAppends(s));     // This code is contributed by unknown2108</script>
2
The above approach is described and O(n**2) approach. 
Efficient Approach:
We also have an algorithm taking the help of the Knuth Morris Pratt Algorithm which is O(n) Time Complexity.
The basic idea behind the approach is that we calculate the largest substring from the end can be calculated and the length of the string minus this value is the minimum number of appends. The logic is intuitive, we need not append the palindrome and only those which do not form the palindrome. To find this largest palindrome from the end, we reverse the string, calculate the DFA and reverse the string again(thus gaining back the original string) and find the final state, which represents the number of matches of the string with the revered string and hence we get the largest substring that is a palindrome from the end, in O(n) time.
Below is the implementation of the above approach:
C++
// CPP program for above approach#include <algorithm>#include <iostream>#include <string>using namespace std; // This class builds the dfa and// precomputes the state.// See KMP algorithm for explanationclass kmp_numeric {private:    int n;    int** dfa; public:    kmp_numeric(string& s)    {        n = s.length();        int c = 256;         // Create dfa        dfa = new int*[n];         // Iterate from 0 to n        for (int i = 0; i < n; i++)            dfa[i] = new int;         int x = 0;         // Iterate from 0 to n        for (int i = 0; i < c; i++)            dfa[0][i] = 0;         // Initialise dfa[0][s[0]] = 1        dfa[0][s[0]] = 1;         // Iterate i from 1 to n-1        for (int i = 1; i < n; i++) {             // Iterate j from 0 to c - 1            for (int j = 0; j < c; j++) {                dfa[i][j] = dfa[x][j];            }             dfa[i][s[i]] = i + 1;            x = dfa[x][s[i]];        }    }     // This function finds the overlap    // between two strings,by    // changing the state.    int longest_overlap(string& query)    {         // q1 is length of query        int ql = query.length();        int state = 0;         // Iterate from 0 to q1 - 1        for (int i = 0; i < ql; i++) {            state = dfa[state][query[i]];        }        return state;    }}; int min_appends(string& s){     // Reverse the string.    reverse(s.begin(), s.end());     // Build the DFA for the    // reversed String    kmp_numeric kmp = s;     // Get the original string back    reverse(s.begin(), s.end());     // Largest overlap in this case is the    // largest string from the end which    // is a palindrome.    int ans = s.length() - kmp.longest_overlap(s);    return ans;} // Driver Codeint main(){    string s = "deep";    // Answer : 3     string t = "sososososos";    // Answer : 0     cout << min_appends(s) << endl;    cout << min_appends(t) << endl;}
3
0
Suggestion by:  Pratik Priyadarsan 
 Related Article : Dynamic Programming | Set 28 (Minimum insertions to form a palindrome)This article is contributed by Shubham Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
Rajput-Ji
29AjayKumar
mohit kumar 29
pratik0718
abhinaygupta98
unknown2108
kumaripunam984122
gulshankumarar231
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java?
Print all the duplicates in the input string
stringstream in C++ and its applications