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.
Input: s = “aabab”
string “ababa” has 9 palindromic substrings: “a”, “b”, “a”, “b”, “a”, “aba”, “bab”, “aba”, “ababa”.
Input: s = “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.
# Python3 program to rearrange the
# string such to maximize the
# number of palindromic substrings
# Function to return the newString
# length of string
l = len(s)
# hashing array
freq =  * (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)
# Driver Code
if __name__ == “__main__”:
s = “aabab”
# This code is contributed by Rituraj Jain
Time Complexity: O(N)
Auxiliary Space: O(26)
- Rearrange given string to maximize the occurrence of string t
- Rearrange the array to maximize the number of primes in prefix sum of the array
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Count of Palindromic substrings in an Index range
- Count all Prime Length Palindromic Substrings
- Number of substrings of a string
- Number of even substrings in a string of digits
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings of one string present in other
- Make palindromic string non-palindromic by rearranging its letters
- Number of strings of length N with no palindromic sub string
- Number of substrings divisible by 6 in a string of integers
- Number of substrings with odd decimal value in a binary string
- Repeat substrings of the given String required number of times
- Count the number of vowels occurring in all the substrings of given 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 firstname.lastname@example.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.