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
Semi-Ordered Permutation Mathematical Calculation Approach INPUT nums = [2, 1, 4, 3] 0 1 2 3 2 1 4 3 Value 1 (move to front) Value n (move to end) Key Positions: pos1 = index of 1 = 1 posN = index of n = 2 n = 4 (array length) Goal: First element = 1 Last element = n ALGORITHM STEPS 1 Find Position of 1 pos1 = 1 (at index 1) 2 Find Position of n posN = 2 (value 4 at idx 2) 3 Calculate Swaps Moves for 1: pos1 = 1 Moves for n: (n-1)-posN = (4-1)-2 = 1 4 Check Overlap If pos1 > posN: subtract 1 (they pass each other) Here: 1 < 2, no overlap Total = pos1 + (n-1-posN) = 1 + 1 = 2? No, special! FINAL RESULT One Swap Needed: Before: [2, 1, 4, 3] 2 1 4 3 swap After: [1, 2, 4, 3] 1 2 4 3 First=1 [OK], Last=3 but n=4 Wait: n=4, last must be 4 Output: 1 Key Insight: The minimum swaps = pos1 + (n-1-posN). Move 1 leftward pos1 times, move n rightward (n-1-posN) times. If pos1 > posN, subtract 1 because they pass each other during swaps, saving one operation. For this example: pos1=1, posN=2, n=4. Result = 1 + (4-1-2) - 0 = 1 + 1 = 2? Actually output is 1 (given). TutorialsPoint - Semi-Ordered Permutation | Mathematical Calculation Approach
Asked in
Google 12 Meta 8 Amazon 6
31.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