← Visualizers
Sliding Window · fixed-size window, circular LeetCode 2134

Minimum Swaps to Group All 1's Together II / visualized

Two traps sit in front of the window here. First, the width is not given to you: if every 1 ends up in one contiguous block, that block is exactly k = total count of 1s wide, so you must derive k before the scan starts. Second, the array is circular — index n-1 sits next to index 0, so the best block may straddle the seam, and a window that quietly stops at the last index is precisely the bug this problem exists to punish. Handle it with modular indexing, nums[(i + k - 1) % n], which is the same thing as conceptually doubling the array — both views are drawn below. Then the live statistic is just the zeros trapped inside the frame, and the answer is k − max ones in any window.

Execution

idle
the array  ·  circular: n−1 is adjacent to 0
 
unrolled  ·  the same window, drawn contiguously
Press Run to begin.
0 / 0
Speed

Java · running line

inside the window entering · (i+k−1) % n leaving · i−1 best window so far outside the window
O(n) time · O(1) space  ·  the width is derived, not given: k = sum(nums). Minimising swaps is minimising zeros inside a width-k circular window, so answer = k - maxOnes.