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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code