Problem Description
Given a string s, the goal is to return all the palindromic permutations (without duplicates) that can be formed using the characters of s. If no palindromic permutation exists, return an empty list.
Key Insights
- A valid palindrome reads the same forwards and backwards.
- In a palindrome, at most one character can have an odd count.
- Count the frequency of each character to verify if a palindrome can be created.
- Use half of each character’s frequency to form one side of the palindrome, then mirror it.
- Backtracking helps in generating unique permutations for the half-string.
Space and Time Complexity
Time Complexity: O(n!) in the worst-case due to generating permutations of the half-string.
Space Complexity: O(n) for the recursion stack and temporary storage during permutation.
Solution
The solution begins by counting character frequencies in the string. It checks whether more than one character has an odd count, which would make a palindromic permutation impossible. If valid, the algorithm identifies a potential middle character (if any) and builds a half-string composed of half the number of occurrences for each character. A backtracking approach is then employed to generate all unique permutations of the half-string. Each unique permutation is mirrored around the middle (if present) to form the complete palindrome.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java with line-by-line comments.