Minimum Right Shifts to Sort the Array - 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.

A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices.

In other words, a right shift moves all elements one position to the right, with the last element wrapping around to the first position.

Input & Output

Example 1 — Rotated Sorted Array
$ Input: nums = [3,4,5,1,2]
Output: 2
💡 Note: Array is rotated sorted. Break point at index 2 (5>1). Need 5-(2+1)=2 right shifts to get [1,2,3,4,5]
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: Array is already sorted, no break points found. Need 0 shifts
Example 3 — Impossible Case
$ Input: nums = [2,1,3,4]
Output: -1
💡 Note: Multiple break points: 2>1 and 4>2 (wraparound). Cannot be sorted by rotation

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • nums contains distinct values

Visualization

Tap to expand
Minimum Right Shifts to Sort Array INPUT Original Array nums[] 3 i=0 4 i=1 5 i=2 1 i=3 2 i=4 Break Point! 5 > 1 (decrease) Rotated Sorted Array 3 4 5 1 2 ALGORITHM STEPS 1 Find Break Point Where nums[i] > nums[i+1] 2 Count Break Points Must be exactly 1 3 Check Wrap-around Last elem less than first 4 Calculate Shifts shifts = n - breakIdx - 1 Calculation: n = 5 breakIdx = 2 (where 5>1) shifts = 5 - 2 - 1 = 2 Answer: 2 right shifts FINAL RESULT Right Shift Animation Original: 3 4 5 1 2 Shift 1: 2 3 4 5 1 Shift 2: 1 2 3 4 5 SORTED! [OK] Output 2 right shifts Key Insight: A rotated sorted array has exactly ONE break point where a larger element precedes a smaller one. The number of right shifts needed = n - breakIndex - 1. If no break point exists, array is already sorted (0 shifts). If multiple break points exist, sorting via rotation is impossible (return -1). Time: O(n), Space: O(1). TutorialsPoint - Minimum Right Shifts to Sort the Array | Optimized - Find Break Point
Asked in
Google 15 Microsoft 12 Amazon 8
24.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen