LeetCode solutions

3045. Minimum Right Shifts to Sort the Array

My accepted Python solution to LeetCode problem 3045, Minimum Right Shifts to Sort the Array, running in 4ms.

  • Difficulty: Easy
  • Python
  • Runtime 4ms
  • Memory 17.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 4ms, memory 17.2MB, accepted 2026-01-01.

python
class Solution:
    def minimumRightShifts(self, nums: List[int]) -> int:
        n = len(nums)
        
        # Find where the "break" point is (where nums[i] > nums[i+1])
        breaks = 0
        break_idx = -1
        
        for i in range(n - 1):
            if nums[i] > nums[i + 1]:
                breaks += 1
                break_idx = i + 1
        
        # If already sorted
        if breaks == 0:
            return 0
        
        # If more than one break, impossible
        if breaks > 1:
            return -1
        
        # Check if rotating at break_idx makes it sorted
        # The last element should be <= first element
        if nums[-1] <= nums[0]:
            return n - break_idx
        
        return -1

Source