Minimum Right Shifts to Sort the Array — LeetCode 2855 Python Solution

EasyArray
Problem
#2855
Reading time
2 min

The 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.

Example

Input
nums = [3,4,5,1,2]
Output
2
Explanation
After the first right shift, nums = [2,3,4,5,1].

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2855. Minimum Right Shifts to Sort the Array?
LeetCode 2855. Minimum Right Shifts to Sort the Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2855. Minimum Right Shifts to Sort the Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2855. Minimum Right Shifts to Sort the Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2855. Minimum Right Shifts to Sort the Array cover?
LeetCode 2855. Minimum Right Shifts to Sort the Array is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview