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.
Time Complexity: O(N)
Auxiliary Space: O(26)
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Rearrange given string to maximize the occurrence of string t
- Rearrange string to obtain Longest Palindromic Substring
- Make palindromic string non-palindromic by rearranging its letters
- Generate a String of having N*N distinct non-palindromic Substrings
- Permutation of given string that maximizes count of Palindromic substrings
- Lexicographically all Shortest Palindromic Substrings from a given string
- Check if a string can be split into even length palindromic substrings
- Check if a Palindromic String can be formed by concatenating Substrings of two given Strings
- Split string into three palindromic substrings with earliest possible cuts
- Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings
- Rearrange the array to maximize the number of primes in prefix sum of the array
- Maximize cost obtained by removal of substrings "pr" or "rp" from a given String
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Count of Palindromic substrings in an Index range
- Count all Prime Length Palindromic Substrings
- Count of K-size substrings having palindromic permutations
- Maximize the number of palindromic Strings
- Rearrange given binary strings to maximize their Bitwise XOR value
- Maximize partitions such that no two substrings have any common character
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.