[LeetCode] Minimum Right Shifts to Sort the Array

2855. Minimum Right Shifts to Sort the Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
bool ok(vector<int>& A, int p) {
int n = A.size();
for(int i = 1; i < A.size(); i++) {
if(A[(p + i) % n] > A[(p + i - 1 + n) % n]) continue;
return false;
}
return true;
}
public:
int minimumRightShifts(vector<int>& nums) {
for(int i = 0; i < nums.size(); i++) {
if(ok(nums,(nums.size() - i) % nums.size())) return i;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/17/PS/LeetCode/minimum-right-shifts-to-sort-the-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.