A string of letters is called a palindrome if it is equal to itself when reversed. You have given a string ‘STR’. Find the number of adjacent swaps you have to make to convert the string into a palindrome.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains a string ‘STR’.
Output Format :
For each test case, print a single integer representing the number of swaps required to convert a string into the palindrome or “-1” if it is impossible to convert it into a palindrome.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| <= 10^3
The string ‘STR’ contains small letters only.
Time Limit : 1 sec
2
mamad
abc
3
-1
For first test case :
First swap “ad” to make string : mamda
Second swap “md” to make string : madma
Third swap “ma” to make string : madam
Final string : madam which is a palindrome.
For second test :
It is impossible to convert the given string into a palindrome, so the output is “-1”.
Think of using a two pointer approach to check the first and last elements of a string.
The basic idea is first to check whether the count of letters present in the string is even or not. A palindrome can maximum consist of 1 odd count letter. Example: madam, pikkkip. Then we can use a two-pointer approach to check for the first letter and last letter simultaneously. If they match, we move forward or count the number of swaps required to make them equal.
Here is the algorithm :
O(N ^ 2), where ‘N’ is the size of the string.
We traverse the letters of the string using the two-pointer approach. If the letters do not match, we use another nested loop to find the matched letter and then swap the letters, which can take a maximum O(N) time. Therefore, the overall time complexity will be O(N ^ 2).
O(1)
We store the count of all letters of the string, which can be a maximum of 26. Therefore, the overall space complexity will be O(1).