Minimum Adjacent Swaps to Make a Valid Array - Problem

You are given a 0-indexed integer array nums. Swaps of adjacent elements are able to be performed on nums.

A valid array meets the following conditions:

  • The largest element (any of the largest elements if there are multiple) is at the rightmost position in the array.
  • The smallest element (any of the smallest elements if there are multiple) is at the leftmost position in the array.

Return the minimum swaps required to make nums a valid array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,5,5,2]
Output: 5
💡 Note: Min element is 2 at index 4, needs 4 swaps to reach index 0. Max element is 5 at index 3 (rightmost occurrence), needs 1 swap to reach index 4. Since min is to the right of max, they cross during swapping, saving 1 swap. Total: 4+1-1=4 swaps.
Example 2 — Elements Cross
$ Input: nums = [9]
Output: 0
💡 Note: Single element array is already valid, no swaps needed.
Example 3 — Min Right of Max
$ Input: nums = [2,4,1,3]
Output: 3
💡 Note: Min(1) at index 2 needs 2 swaps left. Max(4) at index 1 needs 2 swaps right. They cross, so total: 2+2-1=3 swaps.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Adjacent Swaps to Make Valid Array INPUT nums = [3, 4, 5, 5, 2] 3 i=0 4 i=1 5 i=2 MAX 5 i=3 2 i=4 MIN Key Positions: minIdx = 4 (value: 2) maxIdx = 2 (value: 5) Goal: Move MIN to index 0 Move MAX to index n-1 ALGORITHM STEPS 1 Find Positions minIdx=4, maxIdx=2 2 Swaps for MIN minIdx swaps = 4 3 Swaps for MAX (n-1) - maxIdx = 4-2 = 2 4 Check Overlap If minIdx > maxIdx: -1 CALCULATION: minIdx = 4, maxIdx = 2 n = 5 swaps = minIdx + (n-1-maxIdx) swaps = 4 + (4-2) = 4 + 2 Since minIdx > maxIdx: -1 Total = 4 + 2 - 1 = 5? No, 6! FINAL RESULT Swap Sequence: [3,4,5,5,2] --> swap 2 left [3,4,5,2,5] --> swap 2 left [3,4,2,5,5] --> swap 2 left [3,2,4,5,5] --> swap 2 left [2,3,4,5,5] --> 4 swaps [2,3,4,5,5] 5 already at end! But we need 2 more... Valid Array: 2 3 4 5 5 MIN MAX OUTPUT 6 minimum swaps Key Insight: Direct Position Calculation: swaps = minIdx + (n - 1 - maxIdx) If minIdx > maxIdx, subtract 1 (moving min past max position saves one swap). Time: O(n), Space: O(1) - Single pass to find positions, constant space calculation. TutorialsPoint - Minimum Adjacent Swaps to Make a Valid Array | Direct Position Calculation
Asked in
Microsoft 25 Google 20 Amazon 15
23.5K Views
Medium Frequency
~15 min Avg. Time
890 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