Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.
Example 1:
Input: nums = [3,4,5,1,2] Output: 2 Explanation: After the first right shift, nums = [2,3,4,5,1]. After the second right shift, nums = [1,2,3,4,5]. Now nums is sorted; therefore the answer is 2.
Example 2:
Input: nums = [1,3,5] Output: 0 Explanation: nums is already sorted therefore, the answer is 0.
Example 3:
Input: nums = [2,1,4] Output: -1 Explanation: It's impossible to sort the array using right shifts.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100nums contains distinct integers.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[3,4,5,1,2]
[1,3,5]
[2,1,4]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2855: Minimum Right Shifts to Sort the Array
class Solution {
public int minimumRightShifts(List<Integer> nums) {
int n = nums.size();
int i = 1;
while (i < n && nums.get(i - 1) < nums.get(i)) {
++i;
}
int k = i + 1;
while (k < n && nums.get(k - 1) < nums.get(k) && nums.get(k) < nums.get(0)) {
++k;
}
return k < n ? -1 : n - i;
}
}
// Accepted solution for LeetCode #2855: Minimum Right Shifts to Sort the Array
func minimumRightShifts(nums []int) int {
n := len(nums)
i := 1
for i < n && nums[i-1] < nums[i] {
i++
}
k := i + 1
for k < n && nums[k-1] < nums[k] && nums[k] < nums[0] {
k++
}
if k < n {
return -1
}
return n - i
}
# Accepted solution for LeetCode #2855: Minimum Right Shifts to Sort the Array
class Solution:
def minimumRightShifts(self, nums: List[int]) -> int:
n = len(nums)
i = 1
while i < n and nums[i - 1] < nums[i]:
i += 1
k = i + 1
while k < n and nums[k - 1] < nums[k] < nums[0]:
k += 1
return -1 if k < n else n - i
// Accepted solution for LeetCode #2855: Minimum Right Shifts to Sort the Array
fn minimum_right_shifts(nums: Vec<i32>) -> i32 {
let mut min = std::i32::MAX;
let mut min_index = nums.len();
for (i, &num) in nums.iter().enumerate() {
if num < min {
min_index = i;
min = num;
}
}
let mut prev = nums[min_index];
for i in 1..nums.len() {
let index = (min_index + i) % nums.len();
if prev > nums[index] {
return -1;
}
prev = nums[index];
}
((nums.len() - min_index) % nums.len()) as i32
}
fn main() {
let nums = vec![3, 4, 5, 1, 2];
let ret = minimum_right_shifts(nums);
println!("ret={ret}");
}
#[test]
fn test_minimum_right_shifts() {
{
let nums = vec![3, 4, 5, 1, 2];
let ret = minimum_right_shifts(nums);
assert_eq!(ret, 2);
}
{
let nums = vec![1, 3, 5];
let ret = minimum_right_shifts(nums);
assert_eq!(ret, 0);
}
{
let nums = vec![2, 1, 4];
let ret = minimum_right_shifts(nums);
assert_eq!(ret, -1);
}
}
// Accepted solution for LeetCode #2855: Minimum Right Shifts to Sort the Array
function minimumRightShifts(nums: number[]): number {
const n = nums.length;
let i = 1;
while (i < n && nums[i - 1] < nums[i]) {
++i;
}
let k = i + 1;
while (k < n && nums[k - 1] < nums[k] && nums[k] < nums[0]) {
++k;
}
return k < n ? -1 : n - i;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.