Palindrome Permutation II Problem
#267
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 267.
Given a string s, return all the palindromic permutations (without duplicates) of it.
You may return the answer in any order. If s has no palindromic permutation, return an empty list.
Example 1:
Input: s = "aabb"
Output: ["abba","baab"]
Example 2:
Input: s = "abc"
Output: []
Constraints:
1 <= s.length <= 16sconsists of only lowercase English letters.
Solution
Approach: Backtracking on Half the Palindrome
A palindrome is fixed by its left half (and its middle letter, when the length is odd). So we build every distinct left half and mirror it.
- Count the letters. If more than one letter has an odd count, no palindrome exists: return an empty list.
- The letter with an odd count, if there is one, is the middle. Every letter
ccontributescount[c] / 2copies to the left half. - Build the left half by backtracking: at each position try each distinct letter that still has copies left, take one copy, recurse, and put it back. When the half is full, add
half + middle + reverse(half)to the answer.
Trying each distinct letter once per position (instead of each copy) is what avoids duplicates: "aabb" has the half-letters a and b, and the two halves "ab" and "ba" give "abba" and "baab", each once.
Complexity: O(n · P) time, where P is the number of palindromes produced (at most (n/2)!), plus O(n) space for the recursion besides the output.
class Solution:
def generatePalindromes(self, s: str) -> List[str]:
count = [0] * 26
for c in s:
count[ord(c) - ord("a")] += 1
odd = [i for i in range(26) if count[i] % 2 == 1]
if len(odd) > 1:
return [] # at most one letter may sit alone in the middle
middle = chr(odd[0] + ord("a")) if odd else ""
half = [count[i] // 2 for i in range(26)] # copies of each letter left for the left half
answer = []
left = []
def build():
if len(left) == len(s) // 2:
t = "".join(left)
answer.append(t + middle + t[::-1])
return
# Try each distinct letter once per position, so no permutation is built twice.
for i in range(26):
if half[i] > 0:
half[i] -= 1
left.append(chr(i + ord("a")))
build()
left.pop()
half[i] += 1
build()
return answer