Minimum Right Shifts to Sort the Array - Problem
Transform an array into sorted order using right shifts!

Imagine you have an array of distinct positive integers that needs to be sorted, but you can only perform one type of operation: right shifts. In a right shift, every element moves one position to the right, and the last element wraps around to the front.

Your goal is to find the minimum number of right shifts needed to sort the array in ascending order. If it's impossible to sort the array using only right shifts, return -1.

Key insight: An array can be sorted using right shifts if and only if it's a rotation of a sorted array. For example, [3, 4, 5, 1, 2] is a rotation of [1, 2, 3, 4, 5].

Example: [3, 4, 5, 1, 2] โ†’ [2, 3, 4, 5, 1] โ†’ [1, 2, 3, 4, 5] (2 right shifts)

Input & Output

example_1.py โ€” Basic Rotation
$ Input: nums = [3, 4, 5, 1, 2]
โ€บ Output: 2
๐Ÿ’ก Note: The array needs 2 right shifts to become sorted. After 1 right shift: [2, 3, 4, 5, 1]. After 2 right shifts: [1, 2, 3, 4, 5] which is sorted.
example_2.py โ€” Already Sorted
$ Input: nums = [1, 2, 3, 4, 5]
โ€บ Output: 0
๐Ÿ’ก Note: The array is already sorted in ascending order, so no right shifts are needed.
example_3.py โ€” Impossible Case
$ Input: nums = [2, 1, 4, 3]
โ€บ Output: -1
๐Ÿ’ก Note: This array cannot be sorted using only right shifts because it has multiple break points (2>1 and 4>3), indicating it's not a rotation of a sorted array.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i] โ‰ค 100
  • All integers in nums are distinct
  • The array contains only positive integers

Visualization

Tap to expand
Circular Array Right Shift Visualization34512Break Point!5 > 12 shifts neededn - (2 + 1) = 2After 2 right shifts: [1, 2, 3, 4, 5] โœ“
Understanding the Visualization
1
Identify the Pattern
A sortable rotated array has exactly one 'cliff' where a large number drops to a smaller one
2
Find the Break Point
Scan the array to find where nums[i] > nums[i+1] - this is our rotation point
3
Validate Rotation
Check that the last element can connect back to the first (last โ‰ค first)
4
Calculate Shifts
The number of right shifts needed is n - (break_position + 1)
Key Takeaway
๐ŸŽฏ Key Insight: A rotated sorted array has exactly one position where the sequence 'breaks' - finding this break point allows us to calculate the minimum shifts needed in O(n) time.
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
18.9K Views
Medium Frequency
~15 min Avg. Time
847 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