Given string str, the task is to rearrange the given string to obtain the longest palindromic substring.
Examples:
Input: str = “geeksforgeeks”
Output: eegksfskgeeor
Explanation: eegksfskgee is the longest palindromic substring after rearranging the string.
Therefore, the required output is eegksfskgeeor.Input: str = “engineering”
Output: eginenigenr
Approach: The problem can be solved using Hashing. The idea is to count the frequency of each character of the given string. If the count of occurrence of a character exceeds 1, append half(floor value) of its frequency on the left side of the resultant string and the remaining half on the right side of the resultant string. For the remaining characters, append one character in the middle of the resultant string and the rest either at the beginning or at the end of the resultant string. Follow the steps below to solve the problem:
- Initialize an array, say hash[256] to store the frequency of each character.
- To efficiently append the characters on both sides of the resultant string, initialize three strings res1, res2, and res3.
- The string res1 stores the left half of the longest possible palindromic substring, res2 stores the right half of the longest possible palindromic substring, and res3 stores the remaining characters.
- Traverse the hash[] array and for the character, say hash[i], check if its frequency is greater than 1 or not. If found to be true, append the character floor(hash[i]/2) times in res1 and floor(hash[i]/2) times in res2.
- Otherwise, append the first character to not satisfy the above condition to res1 and all the remaining such characters to res3.
- Finally, return the string res1 + reverse(res2) + res3.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;// Function to rearrange the string to // get the longest palindromic substringstring longestPalinSub(string str) { // Stores the length of str int N = str.length(); // Store the count of occurrence // of each character int hash[256] = {0}; // Traverse the string, str for(int i = 0; i < N; i++) { // Count occurrence of // each character hash[str[i]]++; } // Store the left half of the // longest palindromic substring string res1 = ""; // Store the right half of the // longest palindromic substring string res2 = ""; // Traverse the array, hash[] for(int i = 0; i< 256; i++) { // Append half of the // characters to res1 for(int j = 0; j < hash[i] / 2; j++) { res1.push_back(i); } // Append half of the // characters to res2 for(int j = (hash[i] + 1)/2; j < hash[i]; j++) { res2.push_back(i); } } // reverse string res2 to make // res1 + res2 palindrome reverse(res2.begin(), res2.end()); // Store the remaining characters string res3; // Check If any odd character // appended to the middle of // the resultant string or not bool f = false; // Append all the character which // occurs odd number of times for(int i = 0; i < 256; i++) { // If count of occurrence // of characters is odd if(hash[i]%2) { if(!f) { res1.push_back(i); f = true; } else { res3.push_back(i); } } } return (res1 + res2 + res3); }// Driver Codeint main() { string str = "geeksforgeeks"; cout<<longestPalinSub(str);} |
Java
// Java program to implement // the above approach import java.util.*;class GFG{ // Function to rearrange the string to // get the longest palindromic substring static String longestPalinSub(String str) { // Stores the length of str int N = str.length(); // Store the count of occurrence // of each character int[] hash = new int[256]; // Traverse the string, str for(int i = 0; i < N; i++) { // Count occurrence of // each character hash[str.charAt(i)]++; } // Store the left half of the // longest palindromic substring StringBuilder res1 = new StringBuilder(); // Store the right half of the // longest palindromic substring StringBuilder res2 = new StringBuilder(); // Traverse the array, hash[] for(int i = 0; i < 256; i++) { // Append half of the // characters to res1 for(int j = 0; j < hash[i] / 2; j++) { res1.append((char)i); } // Append half of the // characters to res2 for(int j = (hash[i] + 1) / 2; j < hash[i]; j++) { res2.append((char)i); } } // reverse string res2 to make // res1 + res2 palindrome StringBuilder tmp = res2.reverse(); // Store the remaining characters StringBuilder res3 = new StringBuilder(); // Check If any odd character // appended to the middle of // the resultant string or not boolean f = false; // Append all the character which // occurs odd number of times for(int i = 0; i < 256; i++) { // If count of occurrence // of characters is odd if (hash[i] % 2 == 1) { if (!f) { res1.append((char)i); f = true; } else { res3.append((char)i); } } } return (res1.toString() + tmp.toString() + res3.toString()); } // Driver codepublic static void main (String[] args) { String str = "geeksforgeeks"; System.out.println(longestPalinSub(str)); }}// This code is contributed by offbeat |
Python3
# Python 3 program to implement# the above approach# Function to rearrange the # string to get the longest # palindromic substringdef longestPalinSub(st): # Stores the length of # str N = len(st) # Store the count of # occurrence of each # character hash1 = [0] * 256 # Traverse the string, # str for i in range(N): # Count occurrence of # each character hash1[ord(st[i])] += 1 # Store the left half of the # longest palindromic substring res1 = "" # Store the right half of the # longest palindromic substring res2 = "" # Traverse the array, hash[] for i in range(256): # Append half of the # characters to res1 for j in range(hash1[i] // 2): res1 += chr(i) # Append half of the # characters to res2 for j in range((hash1[i] + 1)//2, hash1[i]): res2 += chr(i) # reverse string res2 to make # res1 + res2 palindrome p = list(res2) p.reverse() res2 = ''.join(p) # Store the remaining characters res3 = "" # Check If any odd character # appended to the middle of # the resultant string or not f = False # Append all the character which # occurs odd number of times for i in range(256): # If count of occurrence # of characters is odd if(hash1[i] % 2): if(not f): res1 += chr(i) f = True else: res3 += chr(i) return (res1 + res2 + res3)# Driver Codeif __name__ == "__main__": st = "geeksforgeeks" print(longestPalinSub(st))# This code is contributed by Chitranayal |
C#
// C# program to implement // the above approach using System;using System.Text;class GFG{// Reverse stringstatic String reverse(String input) { char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("", a);} // Function to rearrange the string to // get the longest palindromic substring static String longestPalinSub(String str) { // Stores the length of str int N = str.Length; // Store the count of occurrence // of each character int[] hash = new int[256]; // Traverse the string, str for(int i = 0; i < N; i++) { // Count occurrence of // each character hash[str[i]]++; } // Store the left half of the // longest palindromic substring StringBuilder res1 = new StringBuilder(); // Store the right half of the // longest palindromic substring StringBuilder res2 = new StringBuilder(); // Traverse the array, hash[] for(int i = 0; i < 256; i++) { // Append half of the // characters to res1 for(int j = 0; j < hash[i] / 2; j++) { res1.Append((char)i); } // Append half of the // characters to res2 for(int j = (hash[i] + 1) / 2; j < hash[i]; j++) { res2.Append((char)i); } } // reverse string res2 to make // res1 + res2 palindrome String tmp = reverse(res2.ToString()); // Store the remaining characters StringBuilder res3 = new StringBuilder(); // Check If any odd character // appended to the middle of // the resultant string or not bool f = false; // Append all the character which // occurs odd number of times for(int i = 0; i < 256; i++) { // If count of occurrence // of characters is odd if (hash[i] % 2 == 1) { if (!f) { res1.Append((char)i); f = true; } else { res3.Append((char)i); } } } return (res1.ToString() + tmp.ToString() + res3.ToString()); } // Driver codepublic static void Main(String[] args) { String str = "geeksforgeeks"; Console.WriteLine(longestPalinSub(str)); }}// This code is contributed by Rajput-Ji |
eegksfskgeeor
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Minimum replacements required to obtain a K-periodic palindromic string
- Longest palindromic string possible after removal of a substring
- Minimum length of substring whose rotation generates a palindromic substring
- Rearrange array to obtain maximum possible value of concatenation of prefix GCDs
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Longest Non-palindromic substring
- Longest Palindromic Substring | Set 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
- Suffix Tree Application 6 - Longest Palindromic Substring
- Longest Palindromic Substring | Set 1
- Rearrange the string to maximize the number of palindromic substrings
- Make palindromic string non-palindromic by rearranging its letters
- Longest palindromic string formed by concatenation of prefix and suffix of a string
- Minimum size substring to be removed to make a given string palindromic
- Count characters to be shifted from the start or end of a string to obtain another string
- Find length of longest subsequence of one string which is substring of another string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

