Print all the palindromic permutations of given string in alphabetic order
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Prerequisites: Lexicographically first palindromic string and Next higher palindromic number using the same set of digits.
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.