#2134
Medium Algorithms Minimum swaps to group all 1s together ii
Array Sliding Window
65.6% acceptance
Feb 25, 2026
2076
43
A swap is defined as taking two distinct positions in an array and swapping the values in them.
A circular array is defined as an array where we consider the first element and the last element to be adjacent.
Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_swaps(nums: Vec<i32>) -> i32 {
let k = nums.iter().sum::<i32>() as usize;
if k == 0 {
return 0;
}
let n = nums.len();
// Circular: double the array
// Count zeros in initial window of size k
let mut zeros = nums[..k].iter().filter(|&&x| x == 0).count() as i32;
let mut min_zeros = zeros;
for i in k..n + k {
zeros += (nums[i % n] == 0) as i32;
zeros -= (nums[(i - k) % n] == 0) as i32;
min_zeros = min_zeros.min(zeros);
}
min_zeros
}
}