Palindrome Permutation - Problem

Given a string s, determine if any permutation of the characters in the string can form a palindrome.

A palindrome is a word that reads the same forwards and backwards, like "racecar" or "madam". The key insight is that we don't need to generate all permutations - we just need to check if the character frequencies allow for a palindromic arrangement.

Examples:

  • "aab"true (can form "aba")
  • "carerac"true (can form "racecar")
  • "code"false (no palindromic permutation possible)

Think about it: What property must the character frequencies have for a palindrome to be possible?

Input & Output

example_1.py — Basic case with palindrome possible
$ Input: s = "aab"
Output: true
💡 Note: The string "aab" can be rearranged to form "aba", which is a palindrome. Character frequencies: a=2 (even), b=1 (odd). Since only one character has odd frequency, a palindrome is possible.
example_2.py — No palindrome possible
$ Input: s = "code"
Output: false
💡 Note: The string "code" cannot form any palindrome. Character frequencies: c=1, o=1, d=1, e=1. All characters have odd frequencies (4 odd counts > 1), so no palindromic arrangement is possible.
example_3.py — Perfect palindrome
$ Input: s = "carerac"
Output: true
💡 Note: The string "carerac" can be rearranged to form "racecar". Character frequencies: c=2, a=2, r=2, e=1. Only 'e' has odd frequency, so it can be the center character of a palindrome.

Constraints

  • 0 ≤ s.length ≤ 5000
  • s consists of only lowercase English letters
  • Empty string is considered to have palindromic permutation

Visualization

Tap to expand
Palindrome Mirror PatternExample: "aabcc" → Can form palindrome?Character counts: a=2, b=1, c=2aa✓ Evenb? Oddcc✓ EvenOdd count = 1 ≤ 1 → Palindrome possible!Resulting Palindrome: "acbca"acbcaMirror pairs + center🎯 Key Insight: At most ONE character can have odd frequency!
Understanding the Visualization
1
Count Letter Pairs
For palindrome 'racecar': r-r pair, a-a pair, c-c pair, with 'e' in center
2
Apply Mirror Rule
All letters must have even count (for pairs) except at most one (for center)
3
Verify Pattern
If ≤1 letter has odd count, palindrome arrangement is possible
Key Takeaway
🎯 Key Insight: For any palindrome, characters must form mirror pairs with at most one character in the center position.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
52.0K Views
High Frequency
~8 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen