3942. Minimum Operations to Sort a Permutation
Description
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.
Β
Example 1:
Input: nums = [0,2,1]
Output: 2
Explanation:
- Rotate Left by one:
[2, 1, 0] - Reverse the array:
[0, 1, 2]
The array becomes sorted in 2 operations, which is minimal
Example 2:
Input: nums = [1,0,2]
Output: 2
Explanation:
- Reverse the array:
[2, 0, 1] - Rotate Left by one:
[0, 1, 2]
The array becomes sorted in 2 operations, which is minimal.
Example 3:
Input: nums = [2,0,1,3]
Output: -1
Explanation:
It is impossible to reach [2, 0, 1, 3]. Thus, the answer is -1.
Β
Constraints:
1 <= n == nums.length <= 1050 <= nums[i] <= n - 1numsis a permutation of integers from 0 ton - 1.
Solutions
Solution 1: Case Analysis
We first find the position of 0 in the array, denoted as \(\textit{zero}\).
Next, we check whether the sequence is increasing when traversing right from 0, and whether it is increasing when traversing left from 0.
If it is increasing to the right from 0, we can sort the array in either of the following two ways:
- Rotate directly: left-rotate the array by \(\textit{zero}\) positions.
- Reverse, rotate, then reverse back: reverse the array, left-rotate it by \(n - \textit{zero}\) positions, then reverse it again.
If it is increasing to the left from 0, we can sort the array in either of the following two ways:
- Rotate, then reverse: left-rotate the array by \(\textit{zero} + 1\) positions to move
0to the end, then reverse the array. - Reverse, then rotate: reverse the array, then left-rotate it by \(n - \textit{zero} - 1\) positions to move
0to the beginning.
We compute the number of operations for all four methods above and return the minimum. If sorting is impossible, return -1.
The time complexity is \(O(n)\), where \(n\) is the length of \(\textit{nums}\). The space complexity is \(O(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 | |
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 36 37 38 39 40 41 42 | |
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 | |
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 36 37 38 39 40 41 42 | |
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 | |