You are given a 0-indexed array nums
of length n
. The array nums
can be right-shifted any number of times.
A right shift operation moves the last element of nums
to the front:
nums = [2, 1, 3, 4]
, after one right shift, nums = [4, 2, 1, 3]
.Return the minimum number of right shifts required to sort nums
in non-decreasing order. If it is impossible to sort the array using right shifts, return -1.
Input: nums = [3, 4, 5, 1, 2]
Output: 3
Input: nums = [1, 3, 5]
Output: 0
Input: nums = [2, 1, 3, 4]
Output: -1
nums[i] > nums[i+1]
.0
.-1
.def minimum_right_shifts(nums):
n = len(nums)
pivot = -1
# Finding the pivot
for i in range(n - 1):
if nums[i] > nums[i + 1]:
pivot = i
break
# If pivot is not found, it means array is sorted
if pivot == -1:
return 0
# Check if the array can be sorted with this pivot rotation
for i in range(pivot + 1, n - 1):
if nums[i] > nums[i + 1]:
return -1
# To verify, we need to make sure last element is smaller than first element
if nums[-1] > nums[0]:
return -1
# The minimum shifts needed is length - 1 - pivot
return n - 1 - pivot
# Example Usage
nums = [3, 4, 5, 1, 2]
print(minimum_right_shifts(nums)) # Output: 3
nums = [1, 3, 5]
print(minimum_right_shifts(nums)) # Output: 0
nums = [2, 1, 3, 4]
print(minimum_right_shifts(nums)) # Output: -1
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?