#2855
Minimum Right Shifts to Sort the Array
EasyArrayArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach identifies the pivot point where the array is rotated. If there is only one such pivot, we can calculate the number of shifts needed to sort the array.
⚙️
Algorithm
3 steps- 1Step 1: Find the index of the smallest element in the array (this is the pivot).
- 2Step 2: Check if the array is sorted from the pivot to the end and from the start to the pivot.
- 3Step 3: If the array is sorted, return the index of the pivot as the number of shifts; otherwise, return -1.
solution.py6 lines
1def min_right_shifts(nums):
2 n = len(nums)
3 min_index = nums.index(min(nums))
4 if (min_index == 0 and all(nums[i] <= nums[i + 1] for i in range(n - 1))) or (min_index > 0 and all(nums[i] <= nums[i + 1] for i in range(min_index - 1)) and all(nums[i] <= nums[i + 1] for i in range(min_index, n - 1))):
5 return min_index
6 return -1ℹ
Complexity note: This complexity is achieved by scanning the array once to find the minimum element and checking sorted conditions, which is linear.
- 1The array must have a single pivot point for it to be sortable by right shifts.
- 2If there are multiple points where nums[i] < nums[i-1], sorting is impossible.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.