Given a string s, return every distinct permutation of s that is a palindrome. If no permutation of s reads the same forward and backward, return an empty list.
Function Signature
def generate_palindromes(s: str) -> list[str]:
Rules
-
Each palindrome appears exactly once in the output, even when
s
has repeated letters.
-
Return the palindromes sorted in ascending lexicographic order.
Constraints
-
1 <= len(s) <= 16
-
s
consists of lowercase English letters only.
Examples
Input: s = "aabb"
Output: ["abba", "baab"]
A palindrome of length 4 is fixed by its first two letters, which must be one a and one b. The two orderings "ab" and "ba" give "abba" and "baab".
Input: s = "abc"
Output: []
All three letters appear an odd number of times. A palindrome can have at most one such letter, so none exists.
Input: s = "aaabb"
Output: ["ababa", "baaab"]
The middle letter must be a, the only letter with an odd count. The first two positions then hold one a and one b in either order, which gives exactly these two palindromes.