Minimum Swaps to Group All 1's Together II - Problem
You are given a binary circular array where the first and last elements are considered adjacent. Your goal is to find the minimum number of swaps needed to group all the 1s together in any contiguous segment of the array.

A swap operation exchanges the values at two distinct positions in the array. Since the array is circular, you can think of it as arranged in a circle where position 0 comes right after the last position.

Example: In array [0,1,0,1,1,0,0], we can group all three 1s together by making just 1 swap. We could swap positions to get [0,0,1,1,1,0,0] where all 1s are grouped together.

Your task: Return the minimum number of swaps required to achieve this grouping at any location in the circular array.

Input & Output

example_1.py โ€” Basic case
$ Input: [0,1,0,1,1,0,0]
โ€บ Output: 1
๐Ÿ’ก Note: We need to group 3 ones together. The optimal window contains positions [3,4,5] which has 2 ones and 1 zero. So we need 1 swap to replace the zero with a one from elsewhere.
example_2.py โ€” Circular wrapping
$ Input: [0,1,1,1,0,0,1,1,0]
โ€บ Output: 2
๐Ÿ’ก Note: We have 5 ones total. The best window wraps around: positions [6,7,0,1,2] contains 4 ones and 1 zero. We need 1 swap. Actually, let me recalculate: positions [1,2,3,4,5] has 3 ones and 2 zeros, so we need 2 swaps.
example_3.py โ€” All ones
$ Input: [1,1,1,1]
โ€บ Output: 0
๐Ÿ’ก Note: All elements are already 1, so no swaps are needed.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • nums[i] is either 0 or 1
  • The array is treated as circular

Visualization

Tap to expand
Circular Array: Minimum Swaps to Group 1s01011001Window size = 41s in window = 2Need 2 more 1sSlide this window around the circle to find the position with maximum 1s๐Ÿ”ด = 0 (empty seat)๐ŸŸข = 1 (occupied seat)
Understanding the Visualization
1
Count Total Occupied
First, count how many seats are occupied - this tells us our target window size
2
Find Best Window
Look for a contiguous section of that size which already has the most occupied seats
3
Calculate Swaps
The number of swaps needed equals total occupied minus the maximum occupied found in any window
4
Handle Circular
Since it's circular, the optimal grouping might wrap around from end to beginning
Key Takeaway
๐ŸŽฏ Key Insight: Use sliding window to find the position where we already have the most 1s grouped together. The minimum swaps needed equals total 1s minus the maximum 1s found in any window of optimal size.
Asked in
Amazon 45 Google 38 Meta 28 Microsoft 22
42.3K Views
Medium-High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen