Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [0,1,0,1,1,0,0] Output: 1 Explanation: Here are a few of the ways to group all the 1's together: [0,0,1,1,1,0,0] using 1 swap. [0,1,1,1,0,0,0] using 1 swap. [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). There is no way to group all 1's together with 0 swaps. Thus, the minimum number of swaps required is 1.
Example 2:
Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Explanation: Here are a few of the ways to group all the 1's together: [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). [1,1,1,1,1,0,0,0,0] using 2 swaps. There is no way to group all 1's together with 0 or 1 swaps. Thus, the minimum number of swaps required is 2.
Example 3:
Input: nums = [1,1,0,0,1] Output: 0 Explanation: All the 1's are already grouped together due to the circular property of the array. Thus, the minimum number of swaps required is 0.
Constraints:
1 <= nums.length <= 105nums[i] is either 0 or 1.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Sliding Window
[0,1,0,1,1,0,0]
[0,1,1,1,0,0,1,1,0]
[1,1,0,0,1]
minimum-swaps-to-group-all-1s-together)time-needed-to-rearrange-a-binary-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2134: Minimum Swaps to Group All 1's Together II
class Solution {
public int minSwaps(int[] nums) {
int k = Arrays.stream(nums).sum();
int n = nums.length;
int cnt = 0;
for (int i = 0; i < k; ++i) {
cnt += nums[i];
}
int mx = cnt;
for (int i = k; i < n + k; ++i) {
cnt += nums[i % n] - nums[(i - k + n) % n];
mx = Math.max(mx, cnt);
}
return k - mx;
}
}
// Accepted solution for LeetCode #2134: Minimum Swaps to Group All 1's Together II
func minSwaps(nums []int) int {
k := 0
for _, x := range nums {
k += x
}
cnt := 0
for i := 0; i < k; i++ {
cnt += nums[i]
}
mx := cnt
n := len(nums)
for i := k; i < n+k; i++ {
cnt += nums[i%n] - nums[(i-k+n)%n]
mx = max(mx, cnt)
}
return k - mx
}
# Accepted solution for LeetCode #2134: Minimum Swaps to Group All 1's Together II
class Solution:
def minSwaps(self, nums: List[int]) -> int:
k = nums.count(1)
mx = cnt = sum(nums[:k])
n = len(nums)
for i in range(k, n + k):
cnt += nums[i % n]
cnt -= nums[(i - k + n) % n]
mx = max(mx, cnt)
return k - mx
// Accepted solution for LeetCode #2134: Minimum Swaps to Group All 1's Together II
impl Solution {
pub fn min_swaps(nums: Vec<i32>) -> i32 {
let k: i32 = nums.iter().sum();
let n: usize = nums.len();
let mut cnt: i32 = 0;
for i in 0..k {
cnt += nums[i as usize];
}
let mut mx: i32 = cnt;
for i in k..(n as i32) + k {
cnt += nums[(i % (n as i32)) as usize]
- nums[((i - k + (n as i32)) % (n as i32)) as usize];
mx = mx.max(cnt);
}
return k - mx;
}
}
// Accepted solution for LeetCode #2134: Minimum Swaps to Group All 1's Together II
function minSwaps(nums: number[]): number {
const n = nums.length;
const k = nums.reduce((a, b) => a + b, 0);
let cnt = k - nums.slice(0, k).reduce((a, b) => a + b, 0);
let min = cnt;
for (let i = k; i < n + k; i++) {
cnt += nums[i - k] - nums[i % n];
min = Math.min(min, cnt);
}
return min;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.