Given a string, we need to print all possible palindromes that can be generated using letters of that string.
Input: str = "aabcb" Output: abcba bacab nput: str = "aabbcadad" Output: aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
Generation of palindrome can be done by following steps,
- First we need to check whether letters of string can make a palindrome or not, if not then return.
- After above checking we can make half part of first palindrome string (lexicographically smallest) by taking half frequency of each letter of the given string.
- Now traverse through all possible permutation of this half string and each time add reverse of this part at the end and add odd frequency character in mid between if string is of odd length, for making the palindrome.
Below is C++ implementation.
All palindrome permutations of aabbcadad aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
Let given string is "aabbcadad" Letters have following frequencies : a(4), b(2), c(1), d(2). As all letter has even frequency except one we can make palindromes with the letter of this string. Now half part is – aabd So traversing through all possible permutations of this half string and adding odd frequency character and reverse of string at the end we get following possible palindrome as final result : aabdcdbaa aadbcbdaa abadcdaba abdacadba adabcbada adbacabda baadcdaab badacadab bdaacaadb daabcbaad dabacabad dbaacaabd
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.