
Minimum Adjacent Swaps to Make a Valid Array (medium)
Problem Statement
Given an integer array nums, return the minimum swaps required to make nums a valid array.
You can swap any two adjacent elements of the array.
An array is a valid array if it meets the following conditions:
- The
largestelement is at therightmostposition in the array. - The
smallestelement is at theleftmostposition in the array. - If there are
multiplesmallest and largest elements, any of the smallest elements should be at the leftmost position and any of the largest should be at the rightmost position.
Examples
-
Example 1:
- Input: nums =
[3, 1, 2] - Expected Output:
2 - Justification: The first swap moves
3to the second position by swapping with1, and the second swap moves3to the third position by swapping with2, positioning the smallest element (1) at the beginning and the largest element (3) at the end.
- Input: nums =
-
Example 2:
- Input: nums =
[1, 2, 3, 4] - Expected Output:
0 - Justification: This array already meets the criteria with the smallest element (1) at the start and the largest element (4) at the end, requiring no swaps.
- Input: nums =
-
Example 3:
- Input: nums =
[3, 5, 4, 5, 1, 2] - Expected Output:
5 - Justification: The smallest element (1) requires
4swaps to move to the beginning, and after that the largest element (5) requires1swap to move to the rightmost position, considering the optimal path that minimizes overall swaps.
- Input: nums =
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory