EasyNo. 2855
Minimum Right Shifts to Sort the Array — LeetCode 2855 Python Solution
- Topics
- Array
- Reading time
- 2 min
- Source
- leetcode.com
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
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 - iComplexity
- Time
- O(n)
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
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.