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 TogetherGoal: Group all 1's together with minimum swapsInput:10101Analysis:Total 1's = 3, so window size = 3Best window: [1,0,1] contains 2 onesSwaps needed = 3 - 2 = 1Optimal window positionOutput:1minimum swap needed
Understanding the Visualization
1
Input
Binary array [1,0,1,0,1] with scattered 1's
2
Find Window
Find window of size=ones_count with most 1's
3
Calculate
Swaps = window_size - max_ones_in_window
4
Output
Return minimum swaps needed: 1
Key Takeaway
🎯 Key Insight: Find the window of size k (number of 1's) that already contains the most 1's - this minimizes swaps needed
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