Palindrome Permutation - Problem

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

A palindrome is a word that reads the same forward and backward (e.g., "racecar", "madam").

You need to determine if the characters in the string can be rearranged to form a palindrome, not whether the string itself is already a palindrome.

Example: The string "aab" can be rearranged to "aba", which is a palindrome, so the answer is true.

Input & Output

Example 1 — Can Form Palindrome
$ Input: s = "aab"
Output: true
💡 Note: The string "aab" can be rearranged to "aba" which is a palindrome. Character 'a' appears 2 times (even), 'b' appears 1 time (odd). Since at most one character has odd frequency, a palindrome is possible.
Example 2 — Cannot Form Palindrome
$ Input: s = "carerac"
Output: true
💡 Note: The string "carerac" has character frequencies: 'c'=2, 'a'=2, 'r'=2, 'e'=1. Only one character ('e') has an odd frequency, so a palindrome can be formed, for example "caracer".
Example 3 — Single Character
$ Input: s = "a"
Output: true
💡 Note: A single character is always a palindrome. Character 'a' appears 1 time (odd), which is allowed.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Palindrome Permutation INPUT String s = "aab" a a b idx 0 idx 1 idx 2 Character Count: a count: 2 b count: 1 Can rearrange to form palindrome? "aba" or "baa" --> ALGORITHM STEPS 1 Count Characters Use hashmap/array 'a': 2 'b': 1 2 Count Odd Freqs Track odd counts odd_count = 1 3 Check Condition odd_count <= 1 4 Return Result 1 <= 1 is true Time: O(n) | Space: O(1) FINAL RESULT true Palindrome possible! Valid Arrangement: a b a "aba" reads same forward and backward [OK] Verified Only 1 odd freq (b) Key Insight: A string can form a palindrome if at most ONE character has an odd frequency. Even length palindromes need all even counts. Odd length allows exactly one odd (for the middle). TutorialsPoint - Palindrome Permutation | Optimal Solution
Asked in
Google 25 Facebook 30 Amazon 20 Microsoft 15
125.0K Views
Medium Frequency
~15 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