Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Rearrange string to obtain Longest Palindromic Substring

  • Difficulty Level : Easy
  • Last Updated : 26 May, 2021

Given string str, the task is to rearrange the given string to obtain the longest palindromic substring.

Examples:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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:

  1. Initialize an array, say hash[256] to store the frequency of each character.
  2. To efficiently append the characters on both sides of the resultant string, initialize three strings res1, res2, and res3.
  3. 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.
  4. 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.
  5. Otherwise, append the first character to not satisfy the above condition to res1 and all the remaining such characters to res3.
  6. 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 substring
string 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 Code
int 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 code
public 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 substring
def 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 Code
if __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 string
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);
}
   
// 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 code
public static void Main(String[] args)
{
  String str = "geeksforgeeks";
  Console.WriteLine(longestPalinSub(str));
}
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to rearrange the string to
// get the longest palindromic substring
function longestPalinSub(str)
{
     
    // Stores the length of str
    var N = str.length;
     
    // Store the count of occurrence
    // of each character
    var hash = Array(256).fill(0);
     
    // Traverse the string, str
    for(var i = 0; i < N; i++)
    {
         
        // Count occurrence of
        // each character
        hash[str[i].charCodeAt(0)]++;
    }
     
    // Store the left half of the
    // longest palindromic substring
    var res1 = [];
     
    // Store the right half of the
    // longest palindromic substring
    var res2 = [];
     
    // Traverse the array, hash[]
    for(var i = 0; i< 256; i++)
    {
         
        // Append half of the
        // characters  to res1
        for(var j = 0; j < parseInt(hash[i] / 2); j++)
        {
            res1.push(String.fromCharCode(i));
        }
         
        // Append half of the
        // characters  to res2
        for(var j = parseInt((hash[i] + 1) / 2);
                j < hash[i]; j++)
        {
            res2.push(String.fromCharCode(i));
        }
    }
     
    // Reverse string res2 to make
    // res1 + res2 palindrome
    res2 = res2.reverse();
     
    // Store the remaining characters
    var res3 = [];
     
    // Check If any odd character
    // appended to the middle of
    // the resultant string or not
    var f = false;
     
    // Append all the character which
    // occurs odd number of times
    for(var i = 0; i < 256; i++)
    {
         
        // If count of occurrence
        // of characters is odd
        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(''));   
}
 
// Driver Code
var str = "geeksforgeeks";
document.write(longestPalinSub(str));
 
// This code is contributed by noob2000
 
</script>
Output
eegksfskgeeor

Time Complexity: O(N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!