Leetcode 2855: Minimum Right Shifts to Sort the Array

grid47
grid47
Exploring patterns and algorithms
Jan 26, 2024 5 min read

You are given a list of distinct positive integers. Your task is to determine the minimum number of right shifts needed to sort the list in ascending order, or return -1 if it is not possible.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of distinct positive integers.
Example: nums = [4, 5, 6, 1, 2, 3]
Constraints:
• 1 <= nums.length <= 100
• 1 <= nums[i] <= 100
• nums contains distinct integers.
Output: Return the minimum number of right shifts required to sort the list in ascending order, or -1 if it is not possible.
Example: Output: 3
Constraints:
• The output is an integer, either the number of shifts or -1 if it's impossible.
Goal: Determine if it's possible to sort the list with right shifts and calculate the minimum number of shifts.
Steps:
• Check if the list is already sorted. If it is, return 0.
• If the list is not sorted, check if it can be sorted by performing right shifts. If so, return the number of shifts required.
• If it is not possible to sort the list, return -1.
Goal: Constraints for the input list.
Steps:
• The length of the list is between 1 and 100.
• The list contains distinct integers between 1 and 100.
Assumptions:
• The list contains distinct positive integers.
• The list is cyclic, meaning shifts wrap around the end of the list.
Input: nums = [4, 5, 6, 1, 2, 3]
Explanation: After 3 right shifts, the list becomes sorted as [1, 2, 3, 4, 5, 6].

Input: nums = [1, 2, 3]
Explanation: The list is already sorted, so no right shifts are needed.

Input: nums = [3, 1, 2]
Explanation: It's impossible to sort the list with right shifts because no number of right shifts will sort it.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus