Print all palindrome permutations of a string
Given a string, we need to print all possible palindromes that can be generated using letters of that string. Examples:
Input: str = "aabcb" Output: abcba bacab Input: 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
Time Complexity: O((n/2)!), where n is the length of string and we are finding all possible permutations of half of it.
Auxiliary Space: O(1)
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.