MediumNo. 0267LeetCode Premium
Palindrome Permutation II — LeetCode 267 Python Solution
- Pattern
- Backtracking
- Topics
- Hash Table, String, Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0017 | Letter Combinations of a Phone Number | Medium |
| 0126 | Word Ladder II | Hard |
| 0140 | Word Break II | Hard |
| 0691 | Stickers to Spell Word | Hard |
| 0756 | Pyramid Transition Matrix | Medium |
| 1079 | Letter Tile Possibilities | Medium |
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.