Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Rearrange characters of a string to make it a concatenation of palindromic substrings
Next article icon

Rearrange the string to maximize the number of palindromic substrings

Last Updated : 05 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S consisting of lowercase characters(a-z) only, the task is to print a new string by rearranging the string in such a way that maximizes the number of palindromic substrings. In case of multiple answers, print any one. 

Note: even if some substrings coincide, count them as many times as they appear in the obtained string.

Examples:

Input: s = “aabab” 
Output: ababa 
string “ababa” has 9 palindromic substrings: “a”, “b”, “a”, “b”, “a”, “aba”, “bab”, “aba”, “ababa”.

Input: s = “aa” 
Output: aa 
The given string has the maximum number of palindromic substrings possible, “a”, “a” and “aa”. 

The problem might look to be a complex one but on solving for various cases and having observations will lead to an easy solution. 

A simple solution is to sort the string and print it. Sorting takes O(N * log N). An efficient solution is to count the frequency of each character using a freq[] array and then construct the string using the freq[] array. 

Below is the implementation of the above approach.

C++




// C++ program to rearrange the
// string such to maximize the
// number of palindromic substrings
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the newString
string newString(string s)
{
    // length of string
    int l = s.length();
 
    // hashing array
    int freq[26] = { 0 };
 
    // iterate and count
    for (int i = 0; i < l; i++) {
        freq[s[i] - 'a'] += 1;
    }
 
    // resulting string
    string ans = "";
 
    // form the resulting string
    for (int i = 0; i < 26; i++) {
 
        // number of times character appears
        for (int j = 0; j < freq[i]; j++) {
 
            // append to resulting string
            ans += (char)(97 + i);
        }
    }
 
    return ans;
}
 
// Driver Code
int main()
{
 
    string s = "aabab";
 
    cout << newString(s);
 
    return 0;
}
 
 

Java




// Java program to rearrange the
// string such to maximize the
// number of palindromic substrings
 
 
public class GFG {
     
    // Function to return the newString
    static String newString(String s)
    {
        // length of string
        int l = s.length();
 
        // hashing array
        int freq[] = new int [26] ;
 
        // iterate and count
        for (int i = 0; i < l; i++) {
            freq[s.charAt(i) - 'a'] += 1;
        }
 
        // resulting string
        String ans = "";
 
        // form the resulting string
        for (int i = 0; i < 26; i++) {
 
            // number of times character appears
            for (int j = 0; j < freq[i]; j++) {
 
                // append to resulting string
                ans += (char)(97 + i);
            }
        }
 
        return ans;
    }
 
 
    // Driver code
    public static void main(String args[])
    {
           String s = "aabab";
            System.out.println(newString(s));
    }
    // This Code is contributed by ANKITRAI1
}
 
 

Python3




# Python3 program to rearrange the
# string such to maximize the
# number of palindromic substrings
 
# Function to return the newString
def newString(s):
 
    # length of string
    l = len(s)
 
    # hashing array
    freq = [0] * (26)
 
    # iterate and count
    for i in range(0, l):
        freq[ord(s[i]) - ord('a')] += 1
 
    # resulting string
    ans = ""
 
    # form the resulting string
    for i in range(0, 26):
 
        # number of times character appears
        for j in range(0, freq[i]):
 
            # append to resulting string
            ans += chr(97 + i)
     
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    s = "aabab"
    print(newString(s))
 
# This code is contributed by Rituraj Jain
 
 

C#




// C# program to rearrange the
// string such to maximize the
// number of palindromic substrings
using System;
class GFG
{
 
// Function to return the newString
static String newString(string s)
{
    // length of string
    int l = s.Length;
 
    // hashing array
    int[] freq = new int [26];
 
    // iterate and count
    for (int i = 0; i < l; i++)
    {
        freq[s[i] - 'a'] += 1;
    }
 
    // resulting string
    string ans = "";
 
    // form the resulting string
    for (int i = 0; i < 26; i++)
    {
 
        // number of times character appears
        for (int j = 0; j < freq[i]; j++)
        {
 
            // append to resulting string
            ans += (char)(97 + i);
        }
    }
 
    return ans;
}
 
 
// Driver code
public static void Main()
{
    string s = "aabab";
    Console.Write(newString(s));
}
}
 
// This code is contributed
// by ChitraNayal
 
 

Javascript




<script>
    // Javascript program to rearrange the
    // string such to maximize the
    // number of palindromic substrings
     
    // Function to return the newString
    function newString(s)
    {
        // length of string
        let l = s.length;
 
        // hashing array
        let freq = new Array(26);
        freq.fill(0);
 
        // iterate and count
        for (let i = 0; i < l; i++)
        {
            freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
        }
 
        // resulting string
        let ans = "";
 
        // form the resulting string
        for (let i = 0; i < 26; i++)
        {
 
            // number of times character appears
            for (let j = 0; j < freq[i]; j++)
            {
 
                // append to resulting string
                ans += String.fromCharCode(97 + i);
            }
        }
 
        return ans;
    }
 
     let s = "aabab";
    document.write(newString(s));
     
    // This code is contributed by divyeshrabadiya07.
</script>
 
 
Output
aaabb

Complexity Analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(26)


Next Article
Rearrange characters of a string to make it a concatenation of palindromic substrings

S

Striver
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • Strings
  • Constructive Algorithms
  • palindrome
  • substring
Practice Tags :
  • palindrome
  • Strings

Similar Reads

  • Rearrange string to obtain Longest Palindromic Substring
    Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = “geeksforgeeks”Output: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgee
    9 min read
  • Permutation of given string that maximizes count of Palindromic substrings
    Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.Note: There can be multiple answers for each string. Examples: Input: S = "abcb" Output: "abbc" Explanation: "abbc" is the string with maximum number of palindromic substrin
    3 min read
  • Rearrange characters of a string to make it a concatenation of palindromic substrings
    Given a string S consisting of lowercase alphabets, the task is to check whether the given string can be rearranged such that the string can be split into non-overlapping palindromic substrings of at least length 2. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "
    6 min read
  • Maximize value of Palindrome by rearranging characters of a Substring
    Given a string S of length N (1 ? N ? 103) that consists of a digit from '0' to '9', the task is to find the maximum value of palindrome that could be generated by rearranging characters of a substring. Examples: Input: S = "91242459"Output: 42524Explanation: Rearrange the substring '24245' to form
    14 min read
  • Minimum size substring to be removed to make a given string palindromic
    Given a string S, the task is to print the string after removing the minimum size substring such that S is a palindrome or not. Examples: Input: S = "pqrstsuvwrqp"Output: pqrstsrqpExplanation:Removal of the substring "uvw" modifies S to a palindromic string. Input: S = "geeksforskeeg"Output: geeksfs
    15+ min read
  • Distinct palindromic sub-strings of the given string using Dynamic Programming
    Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been
    8 min read
  • Number of strings of length N with no palindromic sub string
    Given two positive integers N, M. The task is to find the number of strings of length N under the alphabet set of size M such that no substrings of size greater than 1 is palindromic. Examples: Input : N = 2, M = 3 Output : 6 In this case, set of alphabet are 3, say {A, B, C} All possible string of
    5 min read
  • Minimum number of palindromic subsequences to be removed to empty a binary string
    Given a binary string, count minimum number of subsequences to be removed to make it an empty string. Examples : Input: str[] = "10001" Output: 1 Since the whole string is palindrome, we need only one removal. Input: str[] = "10001001" Output: 2 We can remove the middle 1 as first removal, after fir
    6 min read
  • Check if string can be rearranged so that every Odd length Substring is Palindrome
    Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome. Examples: Input: S = "oiooi" Output: YES The string can be rearranged as "oioio" Input: S = "yuyuo" Output: NO Approach: The very first observation is if all
    7 min read
  • Count of Palindromic substrings in an Index range
    Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Ou
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences