Given a string str of size n. The problem is to print all the palindromic permutations of str in alphabetic order if possible else print “-1”.
Input : str = "aabb" Output : abba baab Input : malayalam Output : aalmymlaa aamlylmaa alamymala almayamla amalylama amlayalma laamymaal lamayamal lmaayaaml maalylaam malayalam mlaayaalm
Approach: Following are the steps:
- If possible, find the Lexicographically first palindromic string using the characters of str else print “-1” and return.
- If lexicographically first palindromic string is obtained then print it.
- Now, find the next higher palindromic string using the same set of characters of str. Refer this post.
The only difference between the two posts is that in one digits are being arranged and in the other lowercase characters are being arranged.
- If next higher palindromic string is obtained then print it and goto step 3 else return.
Note that the string str is always manipulated so as to get the palindromic strings using the steps mentioned above.
aalmymlaa aamlylmaa alamymala almayamla amalylama amlayalma laamymaal lamayamal lmaayaaml maalylaam malayalam mlaayaalm
Time Complexity: O(m*n), where m is the number of palindromic permutations of str.