Find if string is K-Palindrome or not | Set 1
Last Updated :
23 Jul, 2025
Given a string S, 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: S = "abcdecba", k = 1
Output: Yes
Explanation: String can become palindrome by removing 1 character i.e. either d or e.
Input: S = "abcdeca", K = 2
Output: Yes
Explanation: Can become palindrome by removing 2 characters b and e.
Input: S= "acdcb", K = 1
Output: No
Explanation: 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 the given string and its reverse as input and the only operation allowed is deletion. Since the given string is compared with its reverse, we will do at most N deletions from the first string and N deletions from the 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 the algorithm:
Process all characters one by one starting from either the left or right sides of both strings. Let us traverse from the right corner, there are two possibilities for every pair of characters being traversed.
- If the last characters of the 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 the last characters are not same, we consider removing operation on last character of first string and last character of the 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.
Below is the Naive recursive implementation of the above approach:
C++
// 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 not
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 + 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 program
int main()
{
string str = "acdcb";
int k = 2;
isKPal(str, k)? cout << "Yes" : cout << "No";
return 0;
}
Java
// A Naive recursive Java program
// to find if given string is
// K-Palindrome or not
import java.util.*;
import java.io.*;
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.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
Python3
# A Naive recursive Python3
# code to find if given string
# is K-Palindrome or not
# Find if given string
# is K-Palindrome or not
def 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 program
string = "acdcb"
k = 2
print("Yes" if isKPal(string, k) else "No")
# This code is contributed by Ansu Kumari.
C#
// A Naive recursive C# program
// to find if given string is
// K-Palindrome or not
using 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
JavaScript
<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>
Time complexity: O(2n), It is exponential. In the worst case, we may end up doing O(2n) operations and the worst case happens string contains all distinct characters.
Auxiliary Space: O(1), since no extra space has been taken.
This problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of the same subproblems can be avoided by constructing a temporary array that stores the results of subproblems .
Below is a Bottom-up implementation of the above recursive approach :
C++
// 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 not
int 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 program
int main()
{
string str = "acdcb";
int k = 2;
isKPal(str, k)? cout << "Yes" : cout << "No";
return 0;
}
Java
// Java program to find if given
// string is K-Palindrome or not
import java.util.*;
import java.io.*;
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.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
Python3
# Python program to find if given
# string is K-Palindrome or not
# Find if given string is
# K-Palindrome or not
def 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 program
string = "acdcb"
k = 2
print("Yes" if isKPal(string, k) else "No")
# This code is contributed by Ansu Kumari.
C#
// C# program to find if given
// string is K-Palindrome or not
using 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
JavaScript
<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>
Time complexity: O(n2), Where n is the length of the given string
Auxiliary Space: O(n2), For creating 2D dp array
Alternate Approach :
1) Find Length of the Longest Palindromic Subsequence
2) If the difference between lengths of the 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem