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 _theminimum swaps required to make _nums
a valid array.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
Solution
Method 1 – Greedy Index Calculation
Intuition
To make the array valid, we need to move the smallest element to the leftmost position and the largest element to the rightmost position. The minimum swaps required are the sum of swaps needed to move the smallest to the front and the largest to the end, adjusting for overlap if they cross.
Approach
- Find the index of the first occurrence of the minimum value (leftmost min).
- Find the index of the last occurrence of the maximum value (rightmost max).
- The swaps to move min to the front is its index.
- The swaps to move max to the end is (n - 1 - index of max).
- If min index is after max index, subtract 1 from the total swaps (since moving min shifts max left).
- Return the total swaps.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- One pass to find min/max and their indices.
- 🧺 Space complexity:
O(1)
- Only a few variables used.