Given a string s, determine whether any anagram of s can form a palindrome. A palindrome reads the same forwards and backwards. An anagram is a rearrangement of characters.
The key insight: a palindrome can have at most one character with an odd frequency. All other characters must appear an even number of times. This is because in a palindrome, characters are paired symmetrically from both ends, and only the middle character (if the length is odd) can be unpaired.
Count the frequency of each character in the string. Then count how many characters have an odd frequency. If this count is 0 or 1, return true; otherwise return false. For an even-length string, all frequencies must be even. For an odd-length string, exactly one character can have an odd frequency.
This solution runs in O(n) time where n is the length of the string, using O(k) space where k is the character set size (constant for ASCII). The algorithm uses a frequency array or a hash map to count character occurrences efficiently.
Edge cases include empty strings (return true), single-character strings (always palindrome), strings with special characters or spaces, and Unicode strings where character representation might differ.
Example Input & Output
Two chars with odd count (a,b,c all odd)
Can be rearranged to aba (palindrome)
Can be rearranged to racecar
racecar itself is a palindrome
Two chars both odd, palindrome impossible
Algorithm Flow

Solution Approach
Determine if any permutation of a string can form a palindrome. A string can form a palindrome if at most one character has an odd frequency. Count character frequencies. If more than one character has an odd count, return false; otherwise return true.
A palindrome can have at most one character with an odd count (the middle character in odd-length strings). All other characters must appear in even numbers.
Time complexity is O(n), space complexity is O(k).
Best Answers
class Solution {
public boolean solution(String s) {
int[] freq = new int[128];
for (int i = 0; i < s.length(); i++) freq[s.charAt(i)]++;
int odd = 0;
for (int v : freq) if (v % 2 != 0) odd++;
return odd <= 1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
