Write an efficient algorithm to check if a given string is k–palindrome or not. A string is k–palindrome if it becomes a palindrome on removing at most k characters from it.

For example,

Input:  ABCDBA, k = 1
Output: k–palindrome
Explanation: The string becomes a palindrome by removing either C or D from it.
 
Input:  ABCDECA, k = 1
Output: Not a k–palindrome
Explanation: The string needs at least 2–removals from it to become a palindrome.

Practice this problem

By carefully analyzing the problem, we can see that it is a variation of the classic Edit Distance Problem, where we need to convert the given string to its reverse by removing at most k characters from it (i.e., only delete operation is allowed).

Please note that we need to perform at most n deletions from the original string and n deletions from the reverse string to make the original string and its reverse equal. Therefore, the expression 2×n <= 2×k is satisfied if the string is k–palindrome.

 
This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The string is k–palindrome

Java


Download  Run Code

Output:

The string is k–palindrome

Python


Download  Run Code

Output:

The string is k–palindrome

The worst-case time complexity of the above solution is O(2n), where n is the length of the input string. The worst case happens when the string contains all different characters. It also requires additional space for the call stack.

The problem has an optimal substructure and exhibits overlapping subproblems. Since both dynamic programming properties are satisfied, we can save subproblem solutions in memory rather than computing them repeatedly. The dynamic programming is demonstrated below in C++, Java, and Python, which runs in O(n2) time:

C++


Download  Run Code

Output:

The string is k–palindrome

Java


Download  Run Code

Output:

The string is k–palindrome

Python


Download  Run Code

Output:

The string is k–palindrome

We can also solve this problem by finding the Longest Palindromic Subsequence (LPS) of a string. To make a string palindrome, the characters that don’t contribute to the LPS should be removed. Therefore, a string is k–palindrome if the difference between the length of LPS and the original string’s length is less than equal to k.

For example, the LPS of string CABCBC is CBCBC, and on removing A from it, the string becomes a palindrome. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The string is k–palindrome

Java


Download  Run Code

Output:

The string is k–palindrome

Python


Download  Run Code

Output:

The string is k–palindrome

The time complexity of the above solution is O(n2) and requires O(n2) extra space, where n is the length of the input string.

 
Author: Aditya Goel