A conveyor loop holds n bins arranged in a line. A right-rotation by one moves every bin one step to the right, wrapping the last bin to the front. Determine the minimum number of right-rotations needed so that the bin values become sorted in non-decreasing order. If no number of rotations can achieve this, report -1.
Line 1: an integer n.
Line 2: n space-separated integers, the bin values.
A single integer: the minimum number of right-rotations that yields a non-decreasing arrangement, or -1 if impossible.
Example 1
Input
5 3 4 5 1 2
Expected
2
Explanation
This is 1 2 3 4 5 rotated right by 2. Rotating right by 2 restores non-decreasing order, and no smaller count works, so the answer is 2.
Example 2
Input
4 1 2 3 4
Expected
0
Explanation
The bins are already non-decreasing, so zero rotations are needed.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →