[LeetCode] Minimum Operations to Sort a Permutation

3942. Minimum Operations to Sort a Permutation

You are given an integer array nums of length n, where nums is a permutation of the integers from 0 to n - 1.

You may perform only the following operations:

  • Reverse the entire array.
  • Rotate Left by One: Move the first element to the end of the array, and rest elements to left by one position.

Return an integer denoting the minimum number of operations required to sort the array in increasing order. If it is not possible to sort the array using only the given operations, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
int minOperations(vector<int>& nums) {
int n = nums.size();
int res = INT_MAX;

bool inc = true;
for(int i = 0; i < n; i++) {
if(nums[i] != (nums[0] + i) % n) {
inc = false;
break;
}
}

if(inc) {
int k = nums[0];
res = min(res, min((n - k) % n, k + 2));
}

bool dec = true;
for(int i = 0; i < n; i++) {
if(nums[i] != (nums[0] - i + n) % n) {
dec = false;
break;
}
}

if(dec) {
int k = (n - 1 - nums[0] + n) % n;
res = min(res, 1 + min(k, (n - k) % n));
}

return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-operations-to-sort-a-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.