Given a string consisting of the first N distinct alphabets, the task is to sort the string by using at most N/2 moves. Each move involves the following:
- Select any 3 distinct indices.
- Perform a cyclic shift on the alphabets at these indices.
If it is possible to sort the strings, print the count of required moves. Otherwise, print “Not Possible”.
Input: str = “cbda”
Selecting the indices 0, 2 and 3 and performing a single circular shift among them, the given string “cbda” is converted to “abcd”.
Input: str = “cba”
Output: Not Possible
In order to solve the problem, follow the steps below:
- Store the integers denoting correct of characters of the string in a vector .
- Place those elements correctly which can all occupy correct indices in a single cycle.
- Traverse an element of the vector
- If the element is not at its sorted index position, check if two or more numbers can be placed at correct indices in one cycle. If the condition is satisfied, perform the cycle otherwise check if there is a distinct index that does not hold the correct element available. If the condition is satisfied, select this index as the third index of the cycle and perform the cycle. If neither of the above conditions are satisfied, sorting would be impossible. Hence, break out of the loop and print “Not Possible”.
- Once a cyclic shift is performed, store the indices involved in the shift.
- If the element is at its sorted position, move to the next index.
- Repeat the above two steps for all vector elements.
- After the traversal is completed, if the entire array is in sorted order, print the shifts required. Else print “Not Possible”.
Below is the implementation of the above approach: