Minimum Swaps to Group All 1's Together explained
Minimum Swaps to Group All 1's Together is a fixed-size window problem in disguise. If the array has m ones, they must end up in some block of length m, and the swaps needed for a block equal the number of zeros inside it. Slide a window of length m, track the most ones it ever holds, and the answer is m minus that maximum, in O(n) time and O(1) space.
By Evin JohnPublished 6 min read
The problem in plain words
You have a list of 0s and 1s. A swap exchanges the values at any two positions, not just neighbors. Find the smallest number of swaps that leaves every 1 in one unbroken run. If there are no 1s, or they are already together, the answer is 0.
| Array | Ones | Swaps | One best final layout |
|---|---|---|---|
[0, 1, 0, 1, 1, 0, 0, 1] | 4 | 1 | Move the last 1 into position 2: [0, 1, 1, 1, 1, 0, 0, 0] |
[1, 0, 0, 0, 1] | 2 | 1 | Swap either 1 next to the other |
[1, 0, 1, 0, 1, 0, 1] | 4 | 2 | Any block of four holds two 1s at best |
[1, 1, 0, 1] | 3 | 1 | Swap the 0 at index 2 with the 1 at index 3: [1, 1, 1, 0] |
[0, 0, 0] | 0 | 0 | Nothing to group |
What the interviewer wants to hear
Two observations carry the whole solution: the target block's length is known (the count of 1s), and the cost of a block is simply how many zeros it contains. Stating both, with a one-line argument for the second, is the moment the problem turns easy. Many candidates instead try to simulate swaps or move 1s toward a median, which works for adjacent swaps but not for this version.
Why zeros inside the block equal the swaps
Fix a block of length m. Say it holds z zeros. Then exactly z ones sit outside it, since there are m ones in total and m - z are inside. One swap can move one outside 1 into one inside 0, so z swaps are enough. And no swap can fix more than one inside zero at a time, so fewer than z swaps cannot work. The best block is the one with the fewest zeros, which is the one with the most ones.
Brute force: check every block
def fewest_swaps_slow(bits):
# try every block where the ones could end up; count zeros inside it
ones = sum(bits)
if ones == 0:
return 0
best = None
for start in range(len(bits) - ones + 1):
zeros_inside = bits[start:start + ones].count(0)
best = zeros_inside if best is None else min(best, zeros_inside)
return bestThat is already correct. With m close to n/2 it is quadratic, and each block shares all but two cells with the previous one, which is the opening for a window.
Sliding window of length m
def fewest_swaps(bits):
ones = sum(bits)
if ones == 0:
return 0
inside = sum(bits[:ones]) # ones already in the first block
most_inside = inside
for right in range(ones, len(bits)):
inside += bits[right] - bits[right - ones]
most_inside = max(most_inside, inside)
return ones - most_inside # each missing one costs one swapfunction fewestSwaps(bits) {
const ones = bits.reduce((a, b) => a + b, 0);
if (ones === 0) return 0;
let inside = 0;
for (let i = 0; i < ones; i++) inside += bits[i];
let mostInside = inside;
for (let right = ones; right < bits.length; right++) {
inside += bits[right] - bits[right - ones];
mostInside = Math.max(mostInside, inside);
}
return ones - mostInside;
}Trace on the first example
[0, 1, 0, 1, 1, 0, 0, 1] has m = 4. The window over indexes 0 to 3 holds two 1s. Slide: indexes 1 to 4 hold three, 2 to 5 hold two, 3 to 6 hold two, 4 to 7 hold two. The most is three, so the answer is 4 - 3 = 1: one zero inside the best block (index 2) trades places with the stray 1 at index 7.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Search over swap sequences | Exponential | Exponential |
| Count zeros in every block | O(n·m) | O(1) |
| Window of length m | O(n) | O(1) |
Edge cases
- No 1s: return 0 before building a window of length 0.
- All 1s: the only window is the whole array, with no zeros, so 0.
- A single 1: any window of length 1 containing it has zero zeros, so 0.
- Ones already contiguous: the window over them holds all m, so 0.
Where people go wrong
- Solving the adjacent-swap version (moving 1s toward their median) when any two positions may be swapped. Ask which kind of swap is allowed.
- Counting the swaps as the number of 1s outside the block divided by two, as if one swap moved two 1s.
- Picking the window length as the number of zeros instead of ones.
- Not handling the circular version when the interviewer adds it (see below).
The circular follow-up
A common variation treats the array as a ring, so a block may wrap from the end back to the start. The same window works if you let the right edge run over 2n positions and read bits[i % n], subtracting bits[(i - m) % n] as cells leave. The answer is still m minus the most ones any window holds. Everything stays O(n).
How to explain it out loud
Fictional example
- Candidate
- Let m be the number of 1s. At the end they fill some block of length m, so I only need to choose where that block goes.
- Candidate
- For a given block, every 0 inside needs exactly one swap with a 1 outside, and one swap can't fix two. So cost equals zeros in the block.
- Candidate
- I'll slide a window of length m, track the most 1s it holds, and return m minus that. Linear time, constant space.
Related problems
Grumpy Bookstore Owner uses the same fixed-size window to find the best place for a block. Binary Subarrays With Sum also counts 1s in windows, but needs exact counts. Longest Repeating Character Replacement asks a similar "how many cells must change" question with a variable window. See the coding problems hub.
Using Natively for practice
While you drill window problems on a Mac or a Windows PC, Natively can read this prompt from a screenshot and check your argument that one swap fixes at most one zero, or help you adapt the window to the circular version. The transcript and notes from the session stay in its history for review. More on the AI interview assistant page.
Questions people ask
How do you solve Minimum Swaps to Group All 1's Together?
Count the 1s, m. Slide a window of length m over the array and track the most 1s any window holds. The answer is m minus that maximum, because each 0 inside the best window needs one swap.
Why does the number of zeros in the window equal the number of swaps?
Each 0 inside the chosen block must be exchanged with a 1 outside it, and one swap can fix only one such 0. So the block's zero count is both enough and necessary.
What is the time complexity of Minimum Swaps to Group All 1's Together?
O(n) time and O(1) extra space with a fixed-size sliding window.
How do you handle the circular version?
Run the window's right edge over 2n positions and read elements with index modulo n, so blocks can wrap around the end. The answer is still the count of 1s minus the most 1s in any window.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
