Problem
Given a string s
, return true
if a permutation of the string could form a palindrome and false
otherwise.
OR
Check if any anagram of a string is a Palindrome or not.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Naive approach of rotating input string
The most straightforward (but highly inefficient) solution is to generate all possible permutations of the input string and check each one to see if it forms a palindrome. If any permutation is a palindrome, return true; otherwise, return false. This brute-force approach is extremely slow for longer strings, since the number of permutations grows factorially with the string length (O(n!)
).
Method 2 - 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.