Magicsheet logo

Minimum Right Shifts to Sort the Array

Easy
77.6%
Updated 6/1/2025

Asked by 2 Companies

Topics

Minimum Right Shifts to Sort the Array

What is this problem about?

The Minimum Right Shifts to Sort the Array problem gives you a circular array and asks for the minimum number of right-rotation shifts needed to sort it in non-decreasing order. A right shift moves the last element to the front. If no number of shifts can sort the array, return -1. This Minimum Right Shifts to Sort the Array interview question is an easy but tricky problem about rotation and sortedness.

Why is this asked in interviews?

Amazon and Accenture ask this to test basic array reasoning and edge case awareness. It's deceptively simple — the easy difficulty rating can catch candidates who overthink it. The core question is: is the array already a rotation of a sorted array? And if so, how many shifts are needed? The array interview pattern applies directly.

Algorithmic pattern used

The approach is linear scan for the rotation point. In a valid right-shifted sorted array, there is exactly one "drop point" — where arr[i] > arr[i+1]. Find this drop. The number of right shifts needed equals n - dropIndex. Additionally, the last element must be ≤ the first element (to close the circular sort). If there are multiple drop points, return -1.

Example explanation

Array: [3, 4, 5, 1, 2].

  • Drop point: index 2 (5 > 1).
  • Last element 2 ≤ first element 3? Yes.
  • Only one drop point → valid rotation.
  • Shifts = 5 - 2 = 3. (Right-shift 3 times: [3,4,5,1,2] → [2,3,4,5,1] → [1,2,3,4,5]).

Array: [2, 1, 4, 3] → two drop points → return -1.

Common mistakes candidates make

  • Not checking whether the last element wraps around correctly with the first element.
  • Returning the drop index instead of n - dropIndex.
  • Not handling the case where the array is already sorted (zero shifts needed).
  • Missing multi-drop detection for unsortable arrays.

Interview preparation tip

Easy problems are often about correctly handling edge cases. For this problem, list all cases before coding: already sorted (0 shifts), one drop point with valid wrap (n - drop shifts), multiple drops (-1), and a single-element array (0 shifts). Drawing the rotation on paper helps. Don't let "easy" difficulty make you skip edge case analysis — interviewers specifically watch for this.

Similar Questions