#C725. Rearrange to Palindrome
Rearrange to Palindrome
Rearrange to Palindrome
You are given a string. Determine whether the characters of the string can be rearranged to form a palindrome. A string is a palindrome if it reads the same backward as forward. If it is possible, output one valid palindrome arrangement. If it is impossible to form a palindrome from the given string, output -1
.
A palindrome has the property that for each character, the number of occurrences is even, with at most one character allowed to appear an odd number of times. In mathematical terms, if you let \( f(c) \) be the frequency of character \( c \), the string can form a palindrome if and only if:
[ \sum_{c \in \text{characters}} [f(c) \mod 2 \neq 0] \leq 1 ]
If a valid palindrome exists, output any one such palindrome. Note that multiple answers may be possible.
inputFormat
The input is given from stdin and consists of multiple test cases. The first line contains an integer \( T \) representing the number of test cases. Each test case consists of a line with an integer \( N \) (the length of the string) followed by a string \( S \) of length \( N \) (separated by a space).
outputFormat
For each test case, print a single line to stdout containing the rearranged palindrome if it exists, or -1
if it is impossible to rearrange the string into a palindrome.
3
4 aabb
5 abcde
6 aaaaaa
abba
-1
aaaaaa
</p>