Description
Given an array nums of distinct integers, return the minimum number of left rotations needed to make the array sorted in non-decreasing order. A left rotation moves the first element to the end of the array. If nums cannot be sorted by any number of left rotations, return -1.
Examples
Input:
nums = [3,4,5,1,2]Output:
3Explanation:
Three left rotations: [3,4,5,1,2] → [4,5,1,2,3] → [5,1,2,3,4] → [1,2,3,4,5].
Input:
nums = [1,2,3,4,5]Output:
0Explanation:
Already sorted; zero rotations needed.
Input:
nums = [2,1,3,4,5]Output:
-1Explanation:
More than one descent in cyclic order; cannot be sorted via rotation.
Input:
nums = [5,1,2,3,4]Output:
1Explanation:
One left rotation yields [1,2,3,4,5].
Constraints
- •
1 ≤ nums.length ≤ 10⁵ - •
-10⁹ ≤ nums[i] ≤ 10⁹ - •
All values in nums are distinct.