Minimum Operations to Sort a Permutation Problem
Description
LeetCode Problem 3942.
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 [0, 1, 2, 3]. Thus, the answer is -1.
Constraints:
1 <= n == nums.length <= 10^50 <= nums[i] <= n - 1numsis a permutation of integers from 0 ton - 1.
Solution
Approach: Case Analysis
Both operations keep the array a circular sequence, possibly read backwards. So the array can be sorted only if, starting from the position zero of the value 0 and walking around the circle in one direction, the values never decrease (and then they are exactly 0, 1, ..., n - 1).
Let zero be the index of 0. We check both walking directions.
- Walking right from 0 is increasing: rotate left
zerotimes, or reverse, rotate leftn - zerotimes and reverse again, which costsn - zero + 2. - Walking left from 0 is increasing: rotate left
zero + 1times to put 0 at the end and reverse, which costszero + 2, or reverse and rotate leftn - zero - 1times, which costsn - zero.
We take the minimum over the cases that apply, or return -1 when neither direction works.
Complexity: O(n) time and O(1) extra space.
from math import inf
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
zero = nums.index(0)
def check(step: int) -> bool:
for i in range(1, n):
prev = (zero + (i - 1) * step) % n
curr = (zero + i * step) % n
if nums[prev] > nums[curr]:
return False
return True
ans = inf
if check(1):
ans = min(ans, zero)
ans = min(ans, n - zero + 2)
if check(-1):
ans = min(ans, zero + 2)
ans = min(ans, n - zero)
return -1 if ans == inf else ans