Minimum Adjacent Swaps to Make a Valid Array - Problem

You are given a 0-indexed integer array nums. Your goal is to transform it into a valid array using the minimum number of adjacent swaps.

A valid array must satisfy both conditions:

  • The largest element (or any of the largest if there are duplicates) must be at the rightmost position
  • The smallest element (or any of the smallest if there are duplicates) must be at the leftmost position

An adjacent swap exchanges two neighboring elements in the array. Return the minimum number of adjacent swaps required to make the array valid.

Example: For array [3, 4, 1, 2], we need to move 1 to the front and 4 to the back, requiring 4 swaps total.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [3,4,1,2]
โ€บ Output: 4
๐Ÿ’ก Note: Min element 1 is at position 2, needs 2 swaps to reach position 0. Max element 4 is at position 1, needs 2 swaps to reach position 3. Since min position (2) > max position (1), their paths cross, so we save 1 swap. Total: 2 + 2 - 1 = 3 swaps.
example_2.py โ€” Already Valid
$ Input: nums = [1,2,3]
โ€บ Output: 0
๐Ÿ’ก Note: Array is already valid: minimum 1 is at leftmost position, maximum 3 is at rightmost position. No swaps needed.
example_3.py โ€” Single Element
$ Input: nums = [5]
โ€บ Output: 0
๐Ÿ’ก Note: Single element array is always valid since the element is both minimum and maximum, and it's already in both leftmost and rightmost positions.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • Adjacent swaps only: Can only exchange neighboring elements

Visualization

Tap to expand
Array Rearrangement VisualizationInitial Array:3412Index: 0 1 2 3Required Movements:Min (1): 2 swaps leftMax (4): 2 swaps rightTarget Array:1324Path Crossing Optimization:โ€ข Min element starts at position 2 (right of max at position 1)โ€ข Their movement paths will cross during rearrangementโ€ข We can save 1 swap by letting them pass each other efficientlyTotal: 2 + 2 - 1 = 3 swaps
Understanding the Visualization
1
Identify Targets
Find the positions of the optimal min and max elements to move
2
Calculate Individual Costs
Count swaps needed to move each element to its target position
3
Optimize Path Crossing
If paths intersect, we can save one swap by letting them pass each other
4
Return Total Cost
Sum up the swaps needed with crossing optimization applied
Key Takeaway
๐ŸŽฏ Key Insight: By identifying the optimal positions for min and max elements and recognizing when their movement paths intersect, we can minimize the total number of adjacent swaps needed to create a valid array.
Asked in
Google 35 Amazon 42 Meta 28 Microsoft 31
42.4K Views
Medium Frequency
~15 min Avg. Time
1.8K 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