Given a string S, the task is to find out the minimum no of adjacent swaps required to make string s palindrome. If it is not possible, then return -1.
Examples:
Input: aabcb
Output: 3
Explanation:
After 1st swap: abacb
After 2nd swap: abcab
After 3rd swap: abcba
Input: adbcdbad
Output: -1
Approach
The following are detailed steps to solve this problem.
- Check whether it is possible to make a palindrome or not from the given string. As we know that if more than one character in a string occurs an odd number of times that string can't be a palindrome.
- If palindrome is not possible then return -1.
- Take two pointers left pointing to the 0th index and a right pointer pointing to the last index to the given string
- Do the following until left pointer is less than right pointer:
- Fix the left pointer and move a copy of right pointer say r, to rightside to search element which is similar to character pointing by left pointer.
- If the left pointer is equal to r pointer, it means this is an odd occurring character that we have to move at the middle of the string.
- So swap character at r index to its next index (move character toward right side)
- Increment result by 1 for this swap operation.
- Otherwise,
- Swap the found character at r to rightside, until it reaches at right index and keeps incrementing the result for the swap operation.
- Increment left by 1 and decrement right by 1.
- Return the result.
Below is the implementation of the above approach:
Time Complexity: O(n2)
Auxiliary Space: O(1)