Minimum Swaps to Group All 1's Together II - Problem

A swap is defined as taking two distinct positions in an array and swapping the values in them.

A circular array is defined as an array where we consider the first element and the last element to be adjacent.

Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.

Input & Output

Example 1 — Basic Circular Array
$ Input: nums = [0,1,0,1,1,0,0]
Output: 1
💡 Note: There are 3 ones total. We need a window of size 3. The best window is [1,1,0] which has only 1 zero, so we need 1 swap to group all 1's together.
Example 2 — All Ones Already
$ Input: nums = [1,1,1,1]
Output: 0
💡 Note: All elements are already 1's, so no swaps are needed to group them together.
Example 3 — Circular Wrapping
$ Input: nums = [1,0,0,0,1]
Output: 0
💡 Note: There are 2 ones. Due to circular nature, we can create a window [1,1] using positions 4 and 0, which has 0 zeros, requiring 0 swaps.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Visualization

Tap to expand
Minimum Swaps to Group All 1's Together II INPUT Circular Binary Array 0 1 0 1 1 0 0 i=0 i=1 i=2 i=3 i=4 i=5 i=6 Linear View: 0 1 0 1 1 0 0 Total 1's = 3 ALGORITHM STEPS 1 Count Total 1's Window size k = 3 2 Sliding Window Slide window of size k 3 Count 0's in Window 0's = swaps needed 4 Find Minimum Track min 0's across all Window Examples: 0 1 0 1 1 0 0 0's: 2 0 1 0 1 1 0 0 0's: 1 0 1 0 1 1 0 0 0's: 1 Min swaps = 1 FINAL RESULT Before (1 swap needed): 0 1 0 1 1 0 0 SWAP After (all 1's grouped): 0 0 1 1 1 0 0 All 1's together! OUTPUT 1 Minimum swaps = 1 OK - Solution verified Key Insight: Use a sliding window of size k (total count of 1's) to find the window with maximum 1's. The minimum swaps needed = k - (max 1's in any window). For circular array, treat it as doubled array or use modulo. Time: O(n), Space: O(1). TutorialsPoint - Minimum Swaps to Group All 1's Together II | Optimal Sliding Window Approach
Asked in
Facebook 25 Amazon 20 Google 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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