Palindrome Permutation II — LeetCode 267 Python Solution

MediumLeetCode PremiumHash TableStringBacktracking
Problem
#267
Reading time
4 min

The problem

Given a string s, return all the palindromic permutations (without duplicates) of it. You may return the answer in any order.

Example

Input
s = "aabb"
Output
["abba","baab"]

Python solution

Python
class Solution:
    def generatePalindromes(self, s: str) -> List[str]:
        def dfs(t):
            if len(t) == len(s):
                ans.append(t)
                return
            for c, v in cnt.items():
                if v > 1:
                    cnt[c] -= 2
                    dfs(c + t + c)
                    cnt[c] += 2

        cnt = Counter(s)
        mid = ''
        for c, v in cnt.items():
            if v & 1:
                if mid:
                    return []
                mid = c
                cnt[c] -= 1
        ans = []
        dfs(mid)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 267. Palindrome Permutation II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 267. Palindrome Permutation II?
LeetCode 267. Palindrome Permutation II is rated Medium on LeetCode.
What is the time complexity of LeetCode 267. Palindrome Permutation II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 267. Palindrome Permutation II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 267. Palindrome Permutation II cover?
LeetCode 267. Palindrome Permutation II is tagged Hash Table, String and Backtracking on LeetCode.
Is LeetCode 267. Palindrome Permutation II a premium problem?
Yes. LeetCode 267. Palindrome Permutation II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview