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
Semi-Ordered Permutation: Queue AnalogyInitial Queue: [2, 1, 4, 3]2143pos 0pos 1pos 2pos 3Target Queue: [1, ?, ?, 4]1??41 step1 stepCalculation:โ€ข Person 1 needs to move 1 position forward (1 step)โ€ข Person 4 needs to move 1 position backward (1 step)Total: 1 + 1 = 2 swaps
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen