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
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
Your task: Return the minimum number of swaps required to achieve this grouping at any location in the circular array.
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code