Skip to main content
Back to problems
#2340
Medium Algorithms

Minimum adjacent swaps to make a valid array

Array Greedy
72.2% acceptance
Mar 31, 2026
196
27
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_swaps(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    if n <= 1 { return 0; }
    // Find leftmost minimum and rightmost maximum
    let mut min_idx = 0;
    let mut max_idx = 0;
    for i in 1..n {
      if nums[i] < nums[min_idx] {
        min_idx = i;
      }
      if nums[i] >= nums[max_idx] {
        max_idx = i;
      }
    }
    let mut swaps = min_idx as i32 + (n - 1 - max_idx) as i32;
    // If min was to the right of max, they cross and we save one swap
    if min_idx > max_idx {
      swaps -= 1;
    }
    swaps
  }
}