Palindrome Permutation
Check whether any permutation of `s` is a palindrome — count odd-frequency letters.
2 min read
hash-map counting
Problem#
Given a string s, return true iff some permutation of s is a palindrome.
Examples#
"code"→false."aab"→true."carerac"→true.
Constraints#
1 <= s.length <= 5000, lowercase letters.
Hints#
Hint
At most one letter can have an odd count.
Approach#
Count letters; sum the parity of each. Answer is oddCount <= 1.
Solution#
class Solution {public: bool canPermutePalindrome(string s) { int cnt[128] = {0}; for (char c : s) ++cnt[(unsigned char)c]; int odd = 0; for (int v : cnt) if (v & 1) ++odd; return odd <= 1; }};func canPermutePalindrome(s string) bool { var cnt [128]int for i := 0; i < len(s); i++ { cnt[s[i]]++ } odd := 0 for _, v := range cnt { if v&1 == 1 { odd++ } } return odd <= 1}from collections import Counter
class Solution: def canPermutePalindrome(self, s: str) -> bool: return sum(v & 1 for v in Counter(s).values()) <= 1function canPermutePalindrome(s) { const cnt = new Map(); for (const c of s) cnt.set(c, (cnt.get(c) ?? 0) + 1); let odd = 0; for (const v of cnt.values()) if (v & 1) odd++; return odd <= 1;}class Solution { public boolean canPermutePalindrome(String s) { int[] cnt = new int[128]; for (int i = 0; i < s.length(); i++) cnt[s.charAt(i)]++; int odd = 0; for (int v : cnt) if ((v & 1) == 1) odd++; return odd <= 1; }}function canPermutePalindrome(s: string): boolean { const cnt: Map<string, number> = new Map(); for (const c of s) cnt.set(c, (cnt.get(c) ?? 0) + 1); let odd = 0; for (const v of cnt.values()) if (v & 1) odd++; return odd <= 1;}Editorial#
A palindrome is symmetric: every letter must pair up except possibly one in the center. Counting odd-frequency letters reduces the check to a single comparison.
Complexity#
- Time: O(N).
- Space: O(1).
Concept revision#
Related#