Minimum Adjacent Swaps to Make a Valid Array Problem
#2340
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2340.
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.
Example 1:
Input: nums = [3,4,5,5,3,1]
Output: 6
Explanation: Perform the following swaps:
- Swap 1: Swap the 3^rd and 4^th elements, nums is then [3,4,5,3,5,1].
- Swap 2: Swap the 4^th and 5^th elements, nums is then [3,4,5,3,1,5].
- Swap 3: Swap the 3^rd and 4^th elements, nums is then [3,4,5,1,3,5].
- Swap 4: Swap the 2^nd and 3^rd elements, nums is then [3,4,1,5,3,5].
- Swap 5: Swap the 1^st and 2^nd elements, nums is then [3,1,4,5,3,5].
- Swap 6: Swap the 0^th and 1^st elements, nums is then [1,3,4,5,3,5].
It can be shown that 6 swaps is the minimum swaps required to make a valid array.
Example 2:
Input: nums = [9]
Output: 0
Explanation: The array is already valid, so we return 0.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Positions of the Extremes
The array is valid when its smallest element is first and its largest is last. Moving the smallest to the front, we should pick its leftmost occurrence (fewest swaps), and moving the largest to the end, we should pick its rightmost occurrence. Let i be the index of the first minimum and j the index of the last maximum, found in one pass.
- If
i == j, one element is both the first minimum and the last maximum, which only happens whenn = 1: it is already valid,0swaps. - Otherwise the minimum needs
iswaps to reach the front and the maximum needsn - 1 - jswaps to reach the end. Ifi < jthese two moves do not interfere, so the answer isi + n - 1 - j. - If
i > j, the two elements cross once, which saves one swap:i + n - 1 - j - 1.
Complexity: Time O(n), space O(1).
class Solution:
def minimumSwaps(self, nums: List[int]) -> int:
i = j = 0
for k, v in enumerate(nums):
if v < nums[i] or (v == nums[i] and k < i):
i = k
if v >= nums[j] or (v == nums[j] and k > j):
j = k
return 0 if i == j else i + len(nums) - 1 - j - (i > j)