1. Description
The array nums contains each integer from 0 through n - 1 exactly once, where n is its length.
In each operation, either reverse nums completely or shift it left by one position, moving its first element to the end. Each reversal or single-position shift counts as one operation.
Return the fewest operations needed to arrange nums in increasing order, or -1 if these operations cannot sort it.
2. Example
Example 1
Input: nums = [0,2,1]
Output: 2
Explanation: A left shift produces [2,1,0], and reversing it produces [0,1,2]. Two operations are necessary and sufficient.
Example 2
Input: nums = [1,0,2]
Output: 2
Explanation: Reversing produces [2,0,1], then a left shift produces [0,1,2]. The minimum is two operations.
Example 3
Input: nums = [2,0,1,3]
Output: -1
Explanation: No combination of full reversals and left shifts can transform this permutation into [0,1,2,3].
3. Constraints
- 1 <= n == nums.length <= 10$^5$
- 0 <= nums[i] <= n - 1
- nums contains every integer from 0 through n - 1 exactly once.
4. Solutions
Case Analysis
n = nums.size()
Time complexity: O(n)
Space complexity: O(1)
| |