Minimum Right Shifts to Sort the Array - Problem
You are given a 0-indexed array nums of length n containing distinct positive integers. Return the minimum number of right shifts required to sort nums and -1 if this is not possible.
A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices.
In other words, a right shift moves all elements one position to the right, with the last element wrapping around to the first position.
Input & Output
Example 1 — Rotated Sorted Array
$
Input:
nums = [3,4,5,1,2]
›
Output:
2
💡 Note:
Array is rotated sorted. Break point at index 2 (5>1). Need 5-(2+1)=2 right shifts to get [1,2,3,4,5]
Example 2 — Already Sorted
$
Input:
nums = [1,2,3,4,5]
›
Output:
0
💡 Note:
Array is already sorted, no break points found. Need 0 shifts
Example 3 — Impossible Case
$
Input:
nums = [2,1,3,4]
›
Output:
-1
💡 Note:
Multiple break points: 2>1 and 4>2 (wraparound). Cannot be sorted by rotation
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 100
- nums contains distinct values
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code