Skip to content

2340. Minimum Adjacent Swaps to Make a Valid Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int minimumSwaps(vector<int>& nums) {
    const int minIndex = getLeftmostMinIndex(nums);
    const int maxIndex = getRightmostMaxIndex(nums);
    const int swaps = minIndex + (nums.size() - 1 - maxIndex);
    return minIndex <= maxIndex ? swaps : swaps - 1;
  }

 private:
  int getLeftmostMinIndex(const vector<int>& nums) {
    int mn = nums.front();
    int minIndex = 0;
    for (int i = 1; i < nums.size(); ++i)
      if (nums[i] < mn) {
        mn = nums[i];
        minIndex = i;
      }
    return minIndex;
  }

  int getRightmostMaxIndex(const vector<int>& nums) {
    int mx = nums.back();
    int maxIndex = nums.size() - 1;
    for (int i = nums.size() - 2; i >= 0; --i)
      if (nums[i] > mx) {
        mx = nums[i];
        maxIndex = i;
      }
    return maxIndex;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public int minimumSwaps(int[] nums) {
    final int minIndex = getLeftmostMinIndex(nums);
    final int maxIndex = getRightmostMaxIndex(nums);
    final int swaps = minIndex + (nums.length - 1 - maxIndex);
    return minIndex <= maxIndex ? swaps : swaps - 1;
  }

  private int getLeftmostMinIndex(int[] nums) {
    int mn = nums[0];
    int minIndex = 0;
    for (int i = 1; i < nums.length; ++i)
      if (nums[i] < mn) {
        mn = nums[i];
        minIndex = i;
      }
    return minIndex;
  }

  int getRightmostMaxIndex(int[] nums) {
    int mx = nums[nums.length - 1];
    int maxIndex = nums.length - 1;
    for (int i = nums.length - 2; i >= 0; --i)
      if (nums[i] > mx) {
        mx = nums[i];
        maxIndex = i;
      }
    return maxIndex;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
  def minimumSwaps(self, nums: list[int]) -> int:
    minIndex = self._getLeftmostMinIndex(nums)
    maxIndex = self._getRightmostMaxIndex(nums)
    swaps = minIndex + (len(nums) - 1 - maxIndex)
    return swaps if minIndex <= maxIndex else swaps - 1

  def _getLeftmostMinIndex(self, nums: list[int]) -> int:
    mn = nums[0]
    minIndex = 0
    for i in range(1, len(nums)):
      if nums[i] < mn:
        mn = nums[i]
        minIndex = i
    return minIndex

  def _getRightmostMaxIndex(self, nums: list[int]) -> int:
    mx = nums[-1]
    maxIndex = len(nums) - 1
    for i in range(len(nums) - 2, -1, -1):
      if nums[i] > mx:
        mx = nums[i]
        maxIndex = i
    return maxIndex