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++
#include <bits/stdc++.h>
using namespace std;
string longestPalinSub(string str) {
int N = str.length();
int hash[256] = {0};
for ( int i = 0; i < N;
i++) {
hash[str[i]]++;
}
string res1 = "" ;
string res2 = "" ;
for ( int i = 0; i< 256; i++) {
for ( int j = 0; j < hash[i] / 2;
j++) {
res1.push_back(i);
}
for ( int j = (hash[i] + 1)/2;
j < hash[i]; j++) {
res2.push_back(i);
}
}
reverse(res2.begin(), res2.end());
string res3;
bool f = false ;
for ( int i = 0; i < 256; i++) {
if (hash[i]%2) {
if (!f) {
res1.push_back(i);
f = true ;
}
else {
res3.push_back(i);
}
}
}
return (res1 + res2 + res3);
}
int main() {
string str = "geeksforgeeks" ;
cout<<longestPalinSub(str);
}
|
Java
import java.util.*;
class GFG{
static String longestPalinSub(String str)
{
int N = str.length();
int [] hash = new int [ 256 ];
for ( int i = 0 ; i < N; i++)
{
hash[str.charAt(i)]++;
}
StringBuilder res1 = new StringBuilder();
StringBuilder res2 = new StringBuilder();
for ( int i = 0 ; i < 256 ; i++)
{
for ( int j = 0 ; j < hash[i] / 2 ; j++)
{
res1.append(( char )i);
}
for ( int j = (hash[i] + 1 ) / 2 ;
j < hash[i]; j++)
{
res2.append(( char )i);
}
}
StringBuilder tmp = res2.reverse();
StringBuilder res3 = new StringBuilder();
boolean f = false ;
for ( int i = 0 ; i < 256 ; i++)
{
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());
}
public static void main (String[] args)
{
String str = "geeksforgeeks" ;
System.out.println(longestPalinSub(str));
}
}
|
Python3
def longestPalinSub(st):
N = len (st)
hash1 = [ 0 ] * 256
for i in range (N):
hash1[ ord (st[i])] + = 1
res1 = ""
res2 = ""
for i in range ( 256 ):
for j in range (hash1[i] / / 2 ):
res1 + = chr (i)
for j in range ((hash1[i] + 1 ) / / 2 ,
hash1[i]):
res2 + = chr (i)
p = list (res2)
p.reverse()
res2 = ''.join(p)
res3 = ""
f = False
for i in range ( 256 ):
if (hash1[i] % 2 ):
if ( not f):
res1 + = chr (i)
f = True
else :
res3 + = chr (i)
return (res1 + res2 + res3)
if __name__ = = "__main__" :
st = "geeksforgeeks"
print (longestPalinSub(st))
|
C#
using System;
using System.Text;
class GFG{
static 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);
}
static String longestPalinSub(String str)
{
int N = str.Length;
int [] hash = new int [256];
for ( int i = 0; i < N; i++)
{
hash[str[i]]++;
}
StringBuilder res1 = new StringBuilder();
StringBuilder res2 = new StringBuilder();
for ( int i = 0; i < 256; i++)
{
for ( int j = 0; j < hash[i] / 2; j++)
{
res1.Append(( char )i);
}
for ( int j = (hash[i] + 1) / 2;
j < hash[i]; j++)
{
res2.Append(( char )i);
}
}
String tmp = reverse(res2.ToString());
StringBuilder res3 = new StringBuilder();
bool f = false ;
for ( int i = 0; i < 256; i++)
{
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());
}
public static void Main(String[] args)
{
String str = "geeksforgeeks" ;
Console.WriteLine(longestPalinSub(str));
}
}
|
Javascript
<script>
function longestPalinSub(str)
{
var N = str.length;
var hash = Array(256).fill(0);
for ( var i = 0; i < N; i++)
{
hash[str[i].charCodeAt(0)]++;
}
var res1 = [];
var res2 = [];
for ( var i = 0; i< 256; i++)
{
for ( var j = 0; j < parseInt(hash[i] / 2); j++)
{
res1.push(String.fromCharCode(i));
}
for ( var j = parseInt((hash[i] + 1) / 2);
j < hash[i]; j++)
{
res2.push(String.fromCharCode(i));
}
}
res2 = res2.reverse();
var res3 = [];
var f = false ;
for ( var i = 0; i < 256; i++)
{
if (hash[i] % 2)
{
if (!f)
{
res1.push(String.fromCharCode(i));
f = true ;
}
else
{
res3.push(String.fromCharCode(i));
}
}
}
return (res1.join( '' ) +
res2.join( '' ) +
res3.join( '' ));
}
var str = "geeksforgeeks" ;
document.write(longestPalinSub(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!