Palindrome Permutation

Check whether any permutation of `s` is a palindrome — count odd-frequency letters.

Easy
Time O(N) Space O(1)
LeetCode
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#

Palindrome Permutation
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.