Semi-Ordered Permutation - Problem
You are given a 0-indexed permutation of n integers called nums. Your goal is to transform this array into a semi-ordered permutation using the minimum number of adjacent swaps.
A permutation is called semi-ordered if:
- The first element equals 1
- The last element equals n
You can perform the following operation as many times as needed:
- Pick any two adjacent elements in the array and swap them
Goal: Return the minimum number of operations needed to make nums a semi-ordered permutation.
Example: Given [2, 1, 4, 3], we need 1 at the start and 4 at the end. The answer is 4 operations: move 1 to the front (1 swap) and move 4 to the end (3 swaps).
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2, 1, 4, 3]
โบ
Output:
4
๐ก Note:
Element 1 is at position 1, needs 1 swap to reach position 0. Element 4 is at position 2, needs 1 swap to reach position 3. Since 1 comes before 4, total is 1 + 1 = 2 swaps. Wait, let me recalculate: 1 needs 1 step left, 4 needs 1 step right, total = 2 swaps.
example_2.py โ Crossing Case
$
Input:
nums = [2, 4, 1, 3]
โบ
Output:
3
๐ก Note:
Element 1 is at position 2, needs 2 swaps to reach position 0. Element 4 is at position 1, needs 2 swaps to reach position 3. Since 1 is initially after 4 (pos(1) > pos(4)), they cross paths and help each other. Total = 2 + 2 - 1 = 3 swaps.
example_3.py โ Already Semi-ordered
$
Input:
nums = [1, 3, 2, 4]
โบ
Output:
0
๐ก Note:
Element 1 is already at position 0, needs 0 swaps. Element 4 is already at position 3 (last position), needs 0 swaps. Total = 0 + 0 = 0 swaps.
Constraints
- 2 โค n โค 50
- 1 โค nums[i] โค n
- nums is a permutation of integers from 1 to n
- Each number from 1 to n appears exactly once
Visualization
Tap to expand
Understanding the Visualization
1
Initial Queue
People are in random order, we need to identify where persons 1 and n are standing
2
Calculate Distances
Count how many positions person 1 needs to move forward and person n needs to move backward
3
Optimal Path
If they need to pass each other, they can help by swapping, saving us one operation
4
Final Result
Sum of individual distances, minus 1 if they cross paths during reorganization
Key Takeaway
๐ฏ Key Insight: Calculate distances mathematically rather than simulating swaps. When elements cross paths, they save one operation by helping each other.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code