Minimum Swaps to Group All 1's Together II (LeetCode 2134): Solution and Explanation

Medium
Array
Sliding Window

Given a binary circular array, find the fewest swaps that gather every 1 into one contiguous block, where the block may wrap from the end of the array back to the start.

Intuition

Count the ones first and call that k. Whatever the final arrangement looks like, the grouped ones fill exactly k adjacent slots on the circle.

Pick any such window of k slots. Each 0 inside it has to be traded for a 1 that sits outside it, and one swap fixes exactly one such pair. So the cost of making that window the group is the number of 0s inside it.

Minimizing 0s inside the window is the same as maximizing 1s inside it, which is a classic fixed-size sliding window. The circle just means indices wrap with % n.

Approach: Circular fixed-size window

  1. Let k = sum(nums). If it is 0, return 0.
  2. Count the 1s in the first window, indices 0 to k-1. Store it as both ones and best.
  3. For i from k to n + k - 1, add nums[i % n] (the slot entering) and subtract nums[(i - k) % n] (the slot leaving).
  4. Update best = max(best, ones) after each slide.
  5. Return k - best, the number of 0s in the fullest window.

Step-by-step example

nums = [0,1,0,1,1,0,0]
  1. There are k = 3 ones, so the group will fill 3 adjacent slots.
  2. Window [0..2] holds 0,1,0: one 1. best = 1.
  3. Slide to [1..3]: slot 3 enters (1), slot 0 leaves (0). ones = 2, best = 2.
  4. Slide to [2..4]: slot 4 enters (1), slot 1 leaves (1). ones = 2. The remaining windows, including the ones that wrap past the end, never hold 3.
  5. The answer is k - best = 3 - 2 = 1 swap.

Code: Python, Java, C++

1class Solution:
2    def minSwaps(self, nums: List[int]) -> int:
3        n = len(nums)
4        k = sum(nums)
5        if k == 0:
6            return 0
7        ones = sum(nums[:k])
8        best = ones
9        for i in range(k, n + k):
10            ones += nums[i % n] - nums[(i - k) % n]
11            best = max(best, ones)
12        return k - best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Counting the ones is one pass, and the window slides n times with constant work per slide.

Space

O(1)

Only a few counters are kept; the wrap is handled with modular indexing instead of copying the array.

Other approaches

Double the array (time O(n), space O(n))

Concatenate nums with itself and run an ordinary sliding window of length k over the first n starting positions. It is the same idea but uses O(n) extra memory.

Prefix sums (time O(n), space O(n))

Build a prefix sum of the doubled array, then the count of 1s in any window is a difference of two prefix values. Useful if you need many window queries.

Common mistakes

  • Forgetting the wrap. Example 3, [1,1,0,0,1], needs 0 swaps only because the window can run off the end and continue at index 0.
  • Not handling k = 0. With no ones the window has length 0; return 0 before building it.
  • Counting 0s outside the window instead of inside. A 0 outside the group is fine; only 0s inside the chosen window need to move.
  • Sliding only n - k times. On a circle every one of the n starting slots is a valid window.

Frequently asked questions

Why does each 0 inside the window cost exactly one swap?

The window has k slots and there are k ones in total, so the number of 0s inside equals the number of 1s outside. Pair them up and swap each pair once; no swap can fix more than one 0.

Why is the window length fixed at k?

The final block contains every 1 and nothing else, so it has exactly k slots. Any shorter window cannot hold all the ones and any longer one would include 0s by definition.

Does it matter where the group ends up?

No. The problem lets the block sit anywhere on the circle, which is why we try every starting slot and keep the cheapest.