Palindrome Permutation — LeetCode 266 Python Solution

EasyLeetCode PremiumBit ManipulationHash TableString
Problem
#266
Reading time
2 min

The problem

Given a string s, return true if a permutation of the string could form a palindrome and false otherwise.

Example

Input
s = "code"
Output
false

Python solution

Python
class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        return sum(v & 1 for v in Counter(s).values()) < 2

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 266. Palindrome Permutation is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 266. Palindrome Permutation?
LeetCode 266. Palindrome Permutation is rated Easy on LeetCode.
What is the time complexity of LeetCode 266. Palindrome Permutation?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 266. Palindrome Permutation?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 266. Palindrome Permutation cover?
LeetCode 266. Palindrome Permutation is tagged Bit Manipulation, Hash Table and String on LeetCode.
Is LeetCode 266. Palindrome Permutation a premium problem?
Yes. LeetCode 266. Palindrome Permutation 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