Semi-Ordered Permutation - Problem
You are given a 0-indexed permutation of n integers nums.
A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation:
- Pick two adjacent elements in
nums, then swap them.
Return the minimum number of operations to make nums a semi-ordered permutation.
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,4,3]
›
Output:
2
💡 Note:
1 is at position 1, needs 1 swap to reach position 0. 4 is at position 2, needs 1 swap to reach position 3. Since 1 is to the left of 4, no optimization possible. Total: 1 + 1 = 2 operations.
Example 2 — Multiple Swaps
$
Input:
nums = [2,4,1,3]
›
Output:
3
💡 Note:
1 is at position 2, needs 2 swaps to reach position 0. 4 is at position 1, needs 2 swaps to reach position 3. But since 1 is to the right of 4, we can optimize by 1 swap. Total: 2 + 2 - 1 = 3 operations.
Example 3 — Already Semi-ordered
$
Input:
nums = [1,3,2,4]
›
Output:
0
💡 Note:
1 is already at position 0 and 4 is already at position 3. The array is already semi-ordered, so 0 operations needed.
Constraints
- 2 ≤ nums.length ≤ 50
- 1 ≤ nums[i] ≤ nums.length
- nums is a permutation of integers from 1 to n
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code