Minimum Swaps to Group All 1's Together - Problem

Given a binary array data, return the minimum number of swaps required to group all 1's present in the array together in any place in the array.

A swap is defined as exchanging the positions of any two elements in the array. The goal is to make all 1's contiguous (adjacent to each other) with the minimum number of swaps.

Note: The 1's can be grouped anywhere in the array - at the beginning, middle, or end.

Input & Output

Example 1 — Basic Case
$ Input: data = [1,0,1,0,1]
Output: 1
💡 Note: We have 3 ones total. The optimal window is either [1,0,1] at positions 0-2 or 2-4, both containing 2 ones and 1 zero. We need 1 swap to make it all ones.
Example 2 — Already Grouped
$ Input: data = [0,0,1,1,1,0,0]
Output: 0
💡 Note: All 3 ones are already grouped together at positions 2-4, so no swaps needed.
Example 3 — All Zeros or Ones
$ Input: data = [1,1,1,1]
Output: 0
💡 Note: All elements are 1s, so they're already grouped together.

Constraints

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

Visualization

Tap to expand
Minimum Swaps to Group All 1's Together INPUT Binary Array: data 1 [0] 0 [1] 1 [2] 0 [3] 1 [4] Total 1's in array: 3 Window size needed: 3 Array length: 5 Goal: Group all 1's together using minimum swaps Use sliding window of size = count of 1's ALGORITHM STEPS 1 Count total 1's ones = 3 (window size) 2 First window [0-2] Count 0's: [1,0,1] has 1 zero 3 Slide window right Track zeros in each window W1: [1,0,1] zeros=1 W2: [0,1,0] zeros=2 W3: [1,0,1] zeros=1 4 Find minimum zeros min(1, 2, 1) = 1 swap swaps = min(zeros in any window of size k) FINAL RESULT Before (1 swap needed): 1 0 1 0 1 Swap index 1 with index 4 After (all 1's grouped): 1 1 1 0 0 Output: 1 Minimum swaps = 1 OK - Optimal! Key Insight: The sliding window technique transforms this problem: instead of counting swaps directly, we count zeros in each window of size k (where k = total 1's). The minimum zeros in any window equals the minimum swaps needed. Time: O(n), Space: O(1). TutorialsPoint - Minimum Swaps to Group All 1's Together | Optimal Sliding Window Approach
Asked in
Microsoft 35 Amazon 28 Facebook 22 Google 18
28.5K Views
Medium Frequency
~15 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