Minimum Right Shifts to Sort the Array Problem
Description
LeetCode Problem 2855.
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.
Example 1:
Input: nums = [3,4,5,1,2]
Output: 2
Explanation:
After the first right shift, nums = [2,3,4,5,1].
After the second right shift, nums = [1,2,3,4,5].
Now nums is sorted; therefore the answer is 2.
Example 2:
Input: nums = [1,3,5]
Output: 0
Explanation: nums is already sorted therefore, the answer is 0.
Example 3:
Input: nums = [2,1,4]
Output: -1
Explanation: It's impossible to sort the array using right shifts.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100numscontains distinct integers.
Solution
Approach: Single Scan
A sorted array that is right-shifted looks like two increasing runs where the second run (the part that wrapped around) is entirely smaller than the first element. Scan from the left to find the end i of the first increasing run, then keep scanning the rest while it keeps increasing and stays below nums[0]. If the scan reaches the end, the array is a rotation of a sorted one and n - i right shifts fix it (this is 0 when it is already sorted). Otherwise return -1.
Complexity: Time O(n), space O(1).
class Solution:
def minimumRightShifts(self, nums: List[int]) -> int:
n = len(nums)
i = 1
while i < n and nums[i - 1] < nums[i]:
i += 1
k = i + 1
while k < n and nums[k - 1] < nums[k] < nums[0]:
k += 1
return -1 if k < n else n - i