Lexicographically first palindromic string
Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message “no palindromic string”. Examples:
Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string
Simple Approach: 1. Sort the string characters in alphabetical(ascending) order. 2. One be one find lexicographically next permutation of the given string. 3. The first permutation which is palindrome is the answer.
Efficient Approach: Properties for palindromic string: 1. If length of string is even, then the frequency of each character in the string must be even. 2. If the length is odd then there should be one character whose frequency is odd and all other chars must have even frequency and at-least one occurrence of the odd character must be present in the middle of the string.
Algorithm 1. Store frequency of each character in the given string 2. Check whether a palindromic string can be formed or not using the properties of palindromic string mentioned above. 3. If palindromic string cannot be formed, return “No Palindromic String”. 4. Else we create three strings and then return front_str + odd_str + rear_str.
- odd_str : It is empty if there is no character with odd frequency. Else it contains all occurrences of odd character.
- front_str : Contains half occurrences of all even occurring characters of string in increasing order.
- rear_str Contains half occurrences of all even occurring characters of string in reverse order of front_str.
Below is implementation of above steps.
Time Complexity : O(n) where n is length of input string. Assuming that size of string alphabet is constant. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...