Minimum Right Shifts to Sort the Array - Problem
Transform an array into sorted order using right shifts!
Imagine you have an array of distinct positive integers that needs to be sorted, but you can only perform one type of operation: right shifts. In a right shift, every element moves one position to the right, and the last element wraps around to the front.
Your goal is to find the minimum number of right shifts needed to sort the array in ascending order. If it's impossible to sort the array using only right shifts, return
Key insight: An array can be sorted using right shifts if and only if it's a rotation of a sorted array. For example,
Example:
Imagine you have an array of distinct positive integers that needs to be sorted, but you can only perform one type of operation: right shifts. In a right shift, every element moves one position to the right, and the last element wraps around to the front.
Your goal is to find the minimum number of right shifts needed to sort the array in ascending order. If it's impossible to sort the array using only right shifts, return
-1.Key insight: An array can be sorted using right shifts if and only if it's a rotation of a sorted array. For example,
[3, 4, 5, 1, 2] is a rotation of [1, 2, 3, 4, 5].Example:
[3, 4, 5, 1, 2] โ [2, 3, 4, 5, 1] โ [1, 2, 3, 4, 5] (2 right shifts) Input & Output
example_1.py โ Basic Rotation
$
Input:
nums = [3, 4, 5, 1, 2]
โบ
Output:
2
๐ก Note:
The array needs 2 right shifts to become sorted. After 1 right shift: [2, 3, 4, 5, 1]. After 2 right shifts: [1, 2, 3, 4, 5] which is sorted.
example_2.py โ Already Sorted
$
Input:
nums = [1, 2, 3, 4, 5]
โบ
Output:
0
๐ก Note:
The array is already sorted in ascending order, so no right shifts are needed.
example_3.py โ Impossible Case
$
Input:
nums = [2, 1, 4, 3]
โบ
Output:
-1
๐ก Note:
This array cannot be sorted using only right shifts because it has multiple break points (2>1 and 4>3), indicating it's not a rotation of a sorted array.
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i] โค 100
- All integers in nums are distinct
- The array contains only positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
A sortable rotated array has exactly one 'cliff' where a large number drops to a smaller one
2
Find the Break Point
Scan the array to find where nums[i] > nums[i+1] - this is our rotation point
3
Validate Rotation
Check that the last element can connect back to the first (last โค first)
4
Calculate Shifts
The number of right shifts needed is n - (break_position + 1)
Key Takeaway
๐ฏ Key Insight: A rotated sorted array has exactly one position where the sequence 'breaks' - finding this break point allows us to calculate the minimum shifts needed in O(n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code