Find longest palindrome formed by removing or shuffling chars from string
Last Updated :
04 Jul, 2022
Given a string, find the longest palindrome that can be constructed by removing or shuffling characters from the string. Return only one palindrome if there are multiple palindrome strings of longest length.
Examples:
Input: abc
Output: a OR b OR c
Input: aabbcc
Output: abccba OR baccab OR cbaabc OR
any other palindromic string of length 6.
Input: abbaccd
Output: abcdcba OR ...
Input: aba
Output: aba
We can divide any palindromic string into three parts - beg, mid and end. For palindromic string of odd length say 2n + 1, 'beg' consists of first n characters of the string, 'mid' will consist of only 1 character i.e. (n + 1)th character and 'end' will consists of last n characters of the palindromic string. For palindromic string of even length 2n, 'mid' will always be empty. It should be noted that 'end' will be reverse of 'beg' in order for string to be palindrome.
The idea is to use above observation in our solution. As shuffling of characters is allowed, order of characters doesn't matter in the input string. We first get frequency of each character in the input string. Then all characters having even occurrence (say 2n) in the input string will be part of the output string as we can easily place n characters in 'beg' string and the other n characters in the 'end' string (by preserving the palindromic order). For characters having odd occurrence (say 2n + 1), we fill 'mid' with one of all such characters. and remaining 2n characters are divided in halves and added at beginning and end.
Below is the implementation of above idea
C++
// C++ program to find the longest palindrome by removing
// or shuffling characters from the given string
#include <bits/stdc++.h>
using namespace std;
// Function to find the longest palindrome by removing
// or shuffling characters from the given string
string findLongestPalindrome(string str)
{
// to stores freq of characters in a string
int count[256] = { 0 };
// find freq of characters in the input string
for (int i = 0; i < str.size(); i++)
count[str[i]]++;
// Any palindromic string consists of three parts
// beg + mid + end
string beg = "", mid = "", end = "";
// solution assumes only lowercase characters are
// present in string. We can easily extend this
// to consider any set of characters
for (char ch = 'a'; ch <= 'z'; ch++)
{
// if the current character freq is odd
if (count[ch] & 1)
{
// mid will contain only 1 character. It
// will be overridden with next character
// with odd freq
mid = ch;
// decrement the character freq to make
// it even and consider current character
// again
count[ch--]--;
}
// if the current character freq is even
else
{
// If count is n(an even number), push
// n/2 characters to beg string and rest
// n/2 characters will form part of end
// string
for (int i = 0; i < count[ch]/2 ; i++)
beg.push_back(ch);
}
}
// end will be reverse of beg
end = beg;
reverse(end.begin(), end.end());
// return palindrome string
return beg + mid + end;
}
// Driver code
int main()
{
string str = "abbaccd";
cout << findLongestPalindrome(str);
return 0;
}
Java
// Java program to find the longest palindrome by removing
// or shuffling characters from the given string
class GFG {
// Function to find the longest palindrome by removing
// or shuffling characters from the given string
static String findLongestPalindrome(String str) {
// to stores freq of characters in a string
int count[] = new int[256];
// find freq of characters in the input string
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
// Any palindromic string consists of three parts
// beg + mid + end
String beg = "", mid = "", end = "";
// solution assumes only lowercase characters are
// present in string. We can easily extend this
// to consider any set of characters
for (char ch = 'a'; ch <= 'z'; ch++) {
// if the current character freq is odd
if (count[ch] % 2 == 1) {
// mid will contain only 1 character. It
// will be overridden with next character
// with odd freq
mid = String.valueOf(ch);
// decrement the character freq to make
// it even and consider current character
// again
count[ch--]--;
} // if the current character freq is even
else {
// If count is n(an even number), push
// n/2 characters to beg string and rest
// n/2 characters will form part of end
// string
for (int i = 0; i < count[ch] / 2; i++) {
beg += ch;
}
}
}
// end will be reverse of beg
end = beg;
end = reverse(end);
// return palindrome string
return beg + mid + end;
}
static String reverse(String str) {
// convert String to character array
// by using toCharArray
String ans = "";
char[] try1 = str.toCharArray();
for (int i = try1.length - 1; i >= 0; i--) {
ans += try1[i];
}
return ans;
}
// Driver code
public static void main(String[] args) {
String str = "abbaccd";
System.out.println(findLongestPalindrome(str));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to find the longest palindrome by removing
# or shuffling characters from the given string
# Function to find the longest palindrome by removing
# or shuffling characters from the given string
def findLongestPalindrome(strr):
# to stores freq of characters in a string
count = [0]*256
# find freq of characters in the input string
for i in range(len(strr)):
count[ord(strr[i])] += 1
# Any palindromic consists of three parts
# beg + mid + end
beg = ""
mid = ""
end = ""
# solution assumes only lowercase characters are
# present in string. We can easily extend this
# to consider any set of characters
ch = ord('a')
while ch <= ord('z'):
# if the current character freq is odd
if (count[ch] & 1):
# mid will contain only 1 character. It
# will be overridden with next character
# with odd freq
mid = ch
# decrement the character freq to make
# it even and consider current character
# again
count[ch] -= 1
ch -= 1
# if the current character freq is even
else:
# If count is n(an even number), push
# n/2 characters to beg and rest
# n/2 characters will form part of end
# string
for i in range(count[ch]//2):
beg += chr(ch)
ch += 1
# end will be reverse of beg
end = beg
end = end[::-1]
# return palindrome string
return beg + chr(mid) + end
# Driver code
strr = "abbaccd"
print(findLongestPalindrome(strr))
# This code is contributed by mohit kumar 29
C#
// C# program to find the longest
// palindrome by removing or
// shuffling characters from
// the given string
using System;
class GFG
{
// Function to find the longest
// palindrome by removing or
// shuffling characters from
// the given string
static String findLongestPalindrome(String str)
{
// to stores freq of characters in a string
int []count = new int[256];
// find freq of characters
// in the input string
for (int i = 0; i < str.Length; i++)
{
count[str[i]]++;
}
// Any palindromic string consists of
// three parts beg + mid + end
String beg = "", mid = "", end = "";
// solution assumes only lowercase
// characters are present in string.
// We can easily extend this to
// consider any set of characters
for (char ch = 'a'; ch <= 'z'; ch++)
{
// if the current character freq is odd
if (count[ch] % 2 == 1)
{
// mid will contain only 1 character.
// It will be overridden with next
// character with odd freq
mid = String.Join("",ch);
// decrement the character freq to make
// it even and consider current
// character again
count[ch--]--;
}
// if the current character freq is even
else
{
// If count is n(an even number), push
// n/2 characters to beg string and rest
// n/2 characters will form part of end
// string
for (int i = 0; i < count[ch] / 2; i++)
{
beg += ch;
}
}
}
// end will be reverse of beg
end = beg;
end = reverse(end);
// return palindrome string
return beg + mid + end;
}
static String reverse(String str)
{
// convert String to character array
// by using toCharArray
String ans = "";
char[] try1 = str.ToCharArray();
for (int i = try1.Length - 1; i >= 0; i--)
{
ans += try1[i];
}
return ans;
}
// Driver code
public static void Main()
{
String str = "abbaccd";
Console.WriteLine(findLongestPalindrome(str));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find the
// longest palindrome by removing
// or shuffling characters from
// the given string
// Function to find the longest
// palindrome by removing
// or shuffling characters from
// the given string
function findLongestPalindrome(str)
{
// to stores freq of characters
// in a string
let count = new Array(256);
for(let i=0;i<256;i++)
{
count[i]=0;
}
// find freq of characters in
// the input string
for (let i = 0; i < str.length; i++) {
count[str[i].charCodeAt(0)]++;
}
// Any palindromic string consists
// of three parts
// beg + mid + end
let beg = "", mid = "", end = "";
// solution assumes only
// lowercase characters are
// present in string.
// We can easily extend this
// to consider any set of characters
for (let ch = 'a'.charCodeAt(0);
ch <= 'z'.charCodeAt(0); ch++) {
// if the current character freq is odd
if (count[ch] % 2 == 1) {
// mid will contain only 1 character. It
// will be overridden with next character
// with odd freq
mid = String.fromCharCode(ch);
// decrement the character freq to make
// it even and consider current character
// again
count[ch--]--;
} // if the current character freq is even
else {
// If count is n(an even number), push
// n/2 characters to beg string and rest
// n/2 characters will form part of end
// string
for (let i = 0; i < count[ch] / 2; i++)
{
beg += String.fromCharCode(ch);
}
}
}
// end will be reverse of beg
end = beg;
end = reverse(end);
// return palindrome string
return beg + mid + end;
}
function reverse(str)
{
// convert String to character array
// by using toCharArray
let ans = "";
let try1 = str.split("");
for (let i = try1.length - 1; i >= 0; i--) {
ans += try1[i];
}
return ans;
}
// Driver code
let str = "abbaccd";
document.write(findLongestPalindrome(str));
// This code is contributed by unknown2108
</script>
Time complexity of above solution is O(n) where n is length of the string. Since, number of characters in the alphabet is constant, they do not contribute to asymptotic analysis.
Auxiliary space used by the program is M where M is number of ASCII characters.
Similar Reads
Palindrome String Coding Problems
A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Palindrome String
Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
13 min read
Check Palindrome by Different Language
Easy Problems on Palindrome
Sentence Palindrome
Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
9 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
14 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
5 min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
13 min read