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: 6
💡 Note: Min element is 2 at index 4, needs 4 swaps to reach index 0. Max element is 5 at index 3, needs 2 swaps to reach index 4. Total: 4+2=6 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 ArrayGoal: Move smallest element to start, largest to end345520123 max4 minInitial Array: [3, 4, 5, 5, 2]4 swaps1 swap23455Valid Array: Total 6 swaps needed
Understanding the Visualization
1
Input Analysis
Array [3,4,5,5,2] - min=2 at index 4, max=5 at index 3
2
Calculate Moves
Min needs 4 swaps left, max needs 2 swaps right
3
Final Result
Total 6 adjacent swaps needed
Key Takeaway
🎯 Key Insight: Calculate distances mathematically - no need to simulate the actual swapping process
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