Palindrome Permutation Problem
Description
LeetCode Problem 266.
Given a string s, return true if a permutation of the string could form a palindrome and false otherwise.
Example 1:
Input: s = "code"
Output: false
Example 2:
Input: s = "aab"
Output: true
Example 3:
Input: s = "carerac"
Output: true
Constraints:
1 <= s.length <= 5000sconsists of only lowercase English letters.
Solution
Approach: Count the Letters
A palindrome reads the same in both directions, so its letters pair up: each letter on the left has a copy on the right. Only the middle letter of an odd-length palindrome is alone.
So a string can be rearranged into a palindrome exactly when at most one letter appears an odd number of times. Count each letter (26 counters are enough), count how many letters have an odd count, and check that it is 0 or 1.
The check works for both lengths: an even-length string must have no odd counts, and an odd-length string has exactly one, because the counts add up to the length.
Complexity: O(n) time and O(1) extra space (26 counters).
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
odd = set() # letters seen an odd number of times so far
for c in s:
if c in odd:
odd.remove(c)
else:
odd.add(c)
# Only the middle letter of a palindrome may appear an odd number of times.
return len(odd) <= 1