Find if string is K-Palindrome or not | Set 1

11 Feb, 2022
Given a string, find out if the string is K-Palindrome or not. A k-palindrome string transforms into a palindrome on removing at most k characters from it.Examples : 
Input : String - abcdecba, k = 1
Output : Yes
String can become palindrome by remo-
-ving 1 character i.e. either d or e)


Input  : String - abcdeca, K = 2
Output : Yes
Can become palindrome by removing
2 characters b and e.

Input : String - acdcb, K = 1
Output : No
String can not become palindrome by
removing only one character.
 
If we carefully analyze the problem, the task is to transform the given string into its reverse by removing at most K characters from it. The problem is basically a variation of Edit Distance. We can modify the Edit Distance problem to consider given string and its reverse as input and only operation allowed is deletion. Since given string is compared with its reverse, we will do at most N deletions from first string and N deletions from second string to make them equal. Therefore, for a string to be k-palindrome, 2*N <= 2*K should hold true.Below are the detailed steps of algorithm –Process all characters one by one starting from either from left or right sides of both strings. Let us traverse from the right corner, there are two possibilities for every pair of character being traversed. 
If last characters of two strings are same, we ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1 where m is length of str1 and n is length of str2.If last characters are not same, we consider remove operation on last character of first string and last character of second string, recursively compute minimum cost for the operations and take minimum of two values.Remove last char from str1: Recur for m-1 and n.Remove last char from str2: Recur for m and n-1.
If last characters of two strings are same, we ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1 where m is length of str1 and n is length of str2.
If last characters are not same, we consider remove operation on last character of first string and last character of second string, recursively compute minimum cost for the operations and take minimum of two values.Remove last char from str1: Recur for m-1 and n.Remove last char from str2: Recur for m and n-1.
Remove last char from str1: Recur for m-1 and n.
Remove last char from str2: Recur for m and n-1.
Below is Naive recursive implementation of above approach.  
C++
Java
Python3
C#
Javascript
// A Naive recursive C++ program to find// if given string is K-Palindrome or not#include<bits/stdc++.h>using namespace std; // find if given string is K-Palindrome or notint isKPalRec(string str1, string str2, int m, int n){    // If first string is empty, the only option is to    // remove all characters of second string    if (m == 0) return n;     // If second string is empty, the only option is to    // remove all characters of first string    if (n == 0) return m;     // If last characters of two strings are same, ignore    // last characters and get count for remaining strings.    if (str1[m-1] == str2[n-1])        return isKPalRec(str1, str2, m-1, n-1);     // If last characters are not same,    // 1. Remove last char from str1 and recur for m-1 and n    // 2. Remove last char from str2 and recur for m and n-1    // Take minimum of above two operations    return 1 + min(isKPalRec(str1, str2, m-1, n), // Remove from str1                   isKPalRec(str1, str2, m, n-1)); // Remove from str2} // Returns true if str is k palindrome.bool isKPal(string str, int k){    string revStr = str;    reverse(revStr.begin(), revStr.end());    int len = str.length();     return (isKPalRec(str, revStr, len, len) <= k*2);} // Driver programint main(){    string str = "acdcb";    int k = 2;    isKPal(str, k)? cout << "Yes" : cout << "No";    return 0;}
// A Naive recursive Java program// to find if given string is// K-Palindrome or notclass GFG{     // find if given string is    // K-Palindrome or not    static int isKPalRec(String str1,            String str2, int m, int n)    {        // If first string is empty,        // the only option is to remove        // all characters of second string        if (m == 0)        {            return n;        }         // If second string is empty,        // the only option is to remove        // all characters of first string        if (n == 0)        {            return m;        }         // If last characters of two        // strings are same, ignore        // last characters and get        // count for remaining strings.        if (str1.charAt(m - 1) ==            str2.charAt(n - 1))        {            return isKPalRec(str1, str2,                            m - 1, n - 1);        }         // If last characters are not same,        // 1. Remove last char from str1 and        // recur for m-1 and n        // 2. Remove last char from str2 and        // recur for m and n-1        // Take minimum of above two operations        return 1 + Math.min(isKPalRec(str1, str2, m - 1, n), // Remove from str1                isKPalRec(str1, str2, m, n - 1)); // Remove from str2    }     // Returns true if str is k palindrome.    static boolean isKPal(String str, int k)    {        String revStr = str;        revStr = reverse(revStr);        int len = str.length();         return (isKPalRec(str, revStr, len, len) <= k * 2);    }     static String reverse(String input)    {        char[] temparray = input.toCharArray();        int left, right = 0;        right = temparray.length - 1;         for (left = 0; left < right; left++, right--)        {            // Swap values of left and right            char temp = temparray[left];            temparray[left] = temparray[right];            temparray[right] = temp;        }        return String.valueOf(temparray);    }     // Driver code    public static void main(String[] args)    {        String str = "acdcb";        int k = 2;        if (isKPal(str, k))        {            System.out.println("Yes");        }        else        {            System.out.println("No");        }    }} // This code is contributed by Rajput-Ji
# A Naive recursive Python3# code to find if given string# is K-Palindrome or not # Find if given string# is K-Palindrome or notdef isKPalRec(str1, str2, m, n):         # If first string is empty,    # the only option is to remove    # all characters of second string    if not m: return n     # If second string is empty,    # the only option is to remove    # all characters of first string    if not n: return m     # If last characters of two strings    # are same, ignore last characters    # and get count for remaining strings.    if str1[m-1] == str2[n-1]:        return isKPalRec(str1, str2, m-1, n-1)     # If last characters are not same,    # 1. Remove last char from str1 and recur for m-1 and n    # 2. Remove last char from str2 and recur for m and n-1    # Take minimum of above two operations    res = 1 + min(isKPalRec(str1, str2, m-1, n),  # Remove from str1                 (isKPalRec(str1, str2, m, n-1))) # Remove from str2                      return res # Returns true if str is k palindrome.def isKPal(string, k):    revStr = string[::-1]    l = len(string)     return (isKPalRec(string, revStr, l, l) <= k * 2)  # Driver programstring = "acdcb"k = 2 print("Yes" if isKPal(string, k) else "No")  # This code is contributed by Ansu Kumari.
// A Naive recursive C# program// to find if given string is// K-Palindrome or notusing System; class GFG{     // find if given string is    // K-Palindrome or not    static int isKPalRec(String str1,            String str2, int m, int n)    {        // If first string is empty,        // the only option is to remove        // all characters of second string        if (m == 0)        {            return n;        }         // If second string is empty,        // the only option is to remove        // all characters of first string        if (n == 0)        {            return m;        }         // If last characters of two        // strings are same, ignore        // last characters and get        // count for remaining strings.        if (str1[m - 1] ==            str2[n - 1])        {            return isKPalRec(str1, str2,                            m - 1, n - 1);        }         // If last characters are not same,        // 1. Remove last char from str1 and        // recur for m-1 and n        // 2. Remove last char from str2 and        // recur for m and n-1        // Take minimum of above two operations        return 1 + Math.Min(isKPalRec(str1, str2, m - 1, n), // Remove from str1                isKPalRec(str1, str2, m, n - 1)); // Remove from str2    }     // Returns true if str is k palindrome.    static bool isKPal(String str, int k)    {        String revStr = str;        revStr = reverse(revStr);        int len = str.Length;         return (isKPalRec(str, revStr, len, len) <= k * 2);    }     static String reverse(String input)    {        char[] temparray = input.ToCharArray();        int left, right = 0;        right = temparray.Length - 1;         for (left = 0; left < right; left++, right--)        {            // Swap values of left and right            char temp = temparray[left];            temparray[left] = temparray[right];            temparray[right] = temp;        }        return String.Join("",temparray);    }     // Driver code    public static void Main(String[] args)    {        String str = "acdcb";        int k = 2;        if (isKPal(str, k))        {            Console.WriteLine("Yes");        }        else        {            Console.WriteLine("No");        }    }} // This code is contributed by 29AjayKumar
<script>// A Naive recursive javascript program// to find if given string is// K-Palindrome or not    // find if given string is    // K-Palindrome or not    function isKPalRec( str1,  str2 , m , n)    {             // If first string is empty,        // the only option is to remove        // all characters of second string        if (m == 0) {            return n;        }         // If second string is empty,        // the only option is to remove        // all characters of first string        if (n == 0) {            return m;        }         // If last characters of two        // strings are same, ignore        // last characters and get        // count for remaining strings.        if (str1.charAt(m - 1) == str2[n - 1]) {            return isKPalRec(str1, str2, m - 1, n - 1);        }         // If last characters are not same,        // 1. Remove last char from str1 and        // recur for m-1 and n        // 2. Remove last char from str2 and        // recur for m and n-1        // Take minimum of above two operations        return 1 + Math.min(isKPalRec(str1, str2, m - 1, n), // Remove from str1                isKPalRec(str1, str2, m, n - 1)); // Remove from str2    }     // Returns true if str is k palindrome.    function isKPal( str , k) {        var revStr = str;        revStr = reverse(revStr);        var len = str.length;         return (isKPalRec(str, revStr, len, len) <= k * 2);    }      function reverse( input) {        var temparray = input;        var left, right = 0;        right = temparray.length - 1;         for (left = 0; left < right; left++, right--)        {                     // Swap values of left and right            var temp = temparray[left];            temparray[left] = temparray[right];            temparray[right] = temp;        }        return temparray;    }     // Driver code             var str = "acdcb";        var k = 2;        if (isKPal(str, k)) {            document.write("Yes");        } else {            document.write("No");        } // This code is contributed by umadevi9616</script>
Output : 
Yes
The time complexity of above solution is exponential. In worst case, we may end up doing O(2n) operations. The worst case happens string contains all distinct characters.This problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems .Below is Bottom-up implementation of above recursive approach : 
C++
Java
Python3
C#
Javascript
// C++ program to find if given string is K-Palindrome or not#include <bits/stdc++.h>using namespace std; // find if given string is K-Palindrome or notint isKPalDP(string str1, string str2, int m, int n){    // Create a table to store results of subproblems    int dp[m + 1][n + 1];     // Fill dp[][] in bottom up manner    for (int i = 0; i <= m; i++)    {        for (int j = 0; j <= n; j++)        {            // If first string is empty, only option is to            // remove all characters of second string            if (i == 0)                dp[i][j] = j; // Min. operations = j             // If second string is empty, only option is to            // remove all characters of first string            else if (j == 0)                dp[i][j] = i; // Min. operations = i             // If last characters are same, ignore last character            // and recur for remaining string            else if (str1[i - 1] == str2[j - 1])                dp[i][j] = dp[i - 1][j - 1];             // If last character are different, remove it            // and find minimum            else             dp[i][j] = 1 + min(dp[i - 1][j], // Remove from str1                             dp[i][j - 1]); // Remove from str2        }    }     return dp[m][n];} // Returns true if str is k palindrome.bool isKPal(string str, int k){    string revStr = str;    reverse(revStr.begin(), revStr.end());    int len = str.length();     return (isKPalDP(str, revStr, len, len) <= k*2);} // Driver programint main(){    string str = "acdcb";    int k = 2;    isKPal(str, k)? cout << "Yes" : cout << "No";    return 0;}
// Java program to find if given// string is K-Palindrome or notclass GFG{     // find if given string is    // K-Palindrome or not    static int isKPalDP(String str1,            String str2, int m, int n)    {                 // Create a table to store        // results of subproblems        int dp[][] = new int[m + 1][n + 1];         // Fill dp[][] in bottom up manner        for (int i = 0; i <= m; i++)        {            for (int j = 0; j <= n; j++)            {                                 // If first string is empty,                // only option is to remove all                // characters of second string                if (i == 0)                {                    // Min. operations = j                    dp[i][j] = j;                }                                 // If second string is empty,                // only option is to remove all                // characters of first string                else if (j == 0)                {                    // Min. operations = i                    dp[i][j] = i;                }                                 // If last characters are same,                // ignore last character and                // recur for remaining string                else if (str1.charAt(i - 1) ==                        str2.charAt(j - 1))                {                    dp[i][j] = dp[i - 1][j - 1];                }                                 // If last character are different,                //  remove it and find minimum                else                {                    // Remove from str1                    // Remove from str2                    dp[i][j] = 1 + Math.min(dp[i - 1][j],                            dp[i][j - 1]);                }            }        }        return dp[m][n];    }     // Returns true if str is k palindrome.    static boolean isKPal(String str, int k)    {        String revStr = str;        revStr = reverse(revStr);        int len = str.length();         return (isKPalDP(str, revStr,                len, len) <= k * 2);    }     static String reverse(String str)    {        StringBuilder sb = new StringBuilder(str);        sb.reverse();        return sb.toString();    }         // Driver program    public static void main(String[] args)    {        String str = "acdcb";        int k = 2;        if (isKPal(str, k))        {            System.out.println("Yes");        }        else        {            System.out.println("No");        }    }} // This code is contributed by// PrinciRaj1992
# Python program to find if given# string is K-Palindrome or not # Find if given string is# K-Palindrome or notdef isKPalDP(str1, str2, m, n):         # Create a table to store    # results of subproblems    dp = [[0] * (n + 1) for _ in range(m + 1)]     # Fill dp[][] in bottom up manner    for i in range(m + 1):                 for j in range(n + 1):                         # If first string is empty,            # only option is to remove            # all characters of second string            if not i :                dp[i][j] = j    # Min. operations = j             # If second string is empty,            # only option is to remove            # all characters of first string            elif not j :                dp[i][j] = i    # Min. operations = i             # If last characters are same,            # ignore last character and            # recur for remaining string            elif (str1[i - 1] == str2[j - 1]):                dp[i][j] = dp[i - 1][j - 1]             # If last character are different,            # remove it and find minimum            else:                dp[i][j] = 1 + min(dp[i - 1][j],  # Remove from str1                                  (dp[i][j - 1])) # Remove from str2     return dp[m][n] # Returns true if str# is k palindrome.def isKPal(string, k):         revStr = string[::-1]    l = len(string)         return (isKPalDP(string, revStr, l, l) <= k * 2)  # Driver programstring = "acdcb"k = 2print("Yes" if isKPal(string, k) else "No")  # This code is contributed by Ansu Kumari.
// C# program to find if given // string is K-Palindrome or notusing System;class GFG {         // find if given string is    // K-Palindrome or not    static int isKPalDP(string str1,             string str2, int m, int n)     {                   // Create a table to store         // results of subproblems        int[,] dp = new int[m + 1, n + 1];           // Fill dp[][] in bottom up manner        for (int i = 0; i <= m; i++)         {            for (int j = 0; j <= n; j++)             {                                   // If first string is empty,                // only option is to remove all                // characters of second string                if (i == 0)                 {                    // Min. operations = j                    dp[i, j] = j;                 }                                    // If second string is empty,                 // only option is to remove all                // characters of first string                else if (j == 0)                 {                    // Min. operations = i                    dp[i, j] = i;                 }                                    // If last characters are same,                 // ignore last character and                // recur for remaining string                else if (str1[i - 1] == str2[j - 1])                 {                    dp[i, j] = dp[i - 1, j - 1];                }                                    // If last character are different,                //  remove it and find minimum                else                {                    // Remove from str1                    // Remove from str2                    dp[i, j] = 1 + Math.Min(dp[i - 1, j], dp[i, j - 1]);                 }            }        }        return dp[m, n];    }         // Returns true if str is k palindrome.    static bool isKPal(string str, int k)    {        string revStr = str;        revStr = reverse(revStr);        int len = str.Length;        return (isKPalDP(str, revStr, len, len) <= k * 2);    }         static string reverse(string str)    {        char[] sb = str.ToCharArray();        Array.Reverse(sb);        return new string(sb);    }         static void Main() {        string str = "acdcb";        int k = 2;        if (isKPal(str, k))         {            Console.WriteLine("Yes");        }         else        {            Console.WriteLine("No");        }    }} // This code is contributed by divyesh072019
<script>// javascript program to find if given// string is K-Palindrome or not    // find if given string is    // K-Palindrome or not    function isKPalDP( str1,  str2 , m , n) {         // Create a table to store        // results of subproblems        var dp = Array(m + 1).fill().map(()=>Array(n + 1).fill(0));         // Fill dp in bottom up manner        for (i = 0; i <= m; i++) {            for (j = 0; j <= n; j++) {                 // If first string is empty,                // only option is to remove all                // characters of second string                if (i == 0) {                    // Min. operations = j                    dp[i][j] = j;                }                 // If second string is empty,                // only option is to remove all                // characters of first string                else if (j == 0) {                    // Min. operations = i                    dp[i][j] = i;                }                 // If last characters are same,                // ignore last character and                // recur for remaining string                else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {                    dp[i][j] = dp[i - 1][j - 1];                }                 // If last character are different,                // remove it and find minimum                else {                    // Remove from str1                    // Remove from str2                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);                }            }        }        return dp[m][n];    }     // Returns true if str is k palindrome.    function isKPal( str , k) {        var revStr = str;        revStr = reverse(revStr);        var len = str.length;         return (isKPalDP(str, revStr, len, len) <= k * 2);    }      function reverse( str) {                 return str.split('').reverse().join('');    }     // Driver program             var str = "acdcb";        var k = 2;        if (isKPal(str, k)) {            document.write("Yes");        } else {            document.write("No");        } // This code is contributed by Rajput-Ji</script>
Output : 
Yes
Time complexity of above solution is O(m x n). We can improve time complexity by making use of the fact that only k deletions are allowed. Auxiliary space used is O(m x n).Alternate Approach : 1) Find Length of the Longest Palindromic Subsequence2) If the difference between lengths of original string and the longest palindromic subsequence is less than or equal k, return true. Else return false.Find if string is K-Palindrome or not | Set 2 (Using LCS)This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 
princiraj1992
Rajput-Ji
29AjayKumar
divyesh072019
akshaysingh98088
umadevi9616
Amazon
LCS
palindrome
subsequence
Dynamic Programming
Amazon
Dynamic Programming
palindrome
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Find if there is a path between two vertices in an undirected graph
Longest Palindromic Substring | Set 1
Longest Increasing Subsequence | DP-3
Bellman–Ford Algorithm | DP-23
Sieve of Eratosthenes
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Count number of binary strings without consecutive 1's