Skip to main content
Back to problems
#2855
Easy Algorithms

Minimum right shifts to sort the array

Array
57.3% acceptance
Feb 25, 2026
243
11
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_right_shifts(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut drops = 0;
    let mut drop_pos = 0;
    for i in 1..n {
      if nums[i] < nums[i-1] { drops += 1; drop_pos = i; }
    }
    if drops == 0 { return 0; }
    if drops > 1 { return -1; }
    // After exactly (n - drop_pos) right shifts, array becomes sorted
    // Valid only if the wrap-around is consistent: nums[n-1] < nums[0]
    if nums[n-1] >= nums[0] { return -1; }
    (n - drop_pos) as i32
  }
}