Problem
Given a string s
, return true
if a permutation of the string could form a palindrome and false
otherwise.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Using Frequency Map
For a string to be rearranged into a palindrome:
- All characters must appear an even number of times, allowing them to be mirrored around the centre, except for at most one character which can appear an odd number of times (this would be the centre character in an odd-length palindrome).
Approach
- Count the frequency of each character in the string.
- Check how many characters have an odd frequency.
- If more than one character has an odd frequency, return
false
; otherwise, returntrue
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the string. This is due to counting the frequency of characters and then checking the counts. - 🧺 Space complexity:
O(1)
if only considering the fixed number of possible characters (e.g., ASCII or a limited character set). This is because the space for counting is constant irrespective of the length of string.