Facebook Pixel

Minimum Swaps to Group All 1's Together

Medium
LeetCode ↗

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.

Example 1:

Input: data = [1,0,1,0,1]
Output: 1
Explanation: There are 3 ways to group all 1's together: [1,1,1,0,0] using 1 swap. [0,1,1,1,0] using 2 swaps. [0,0,1,1,1] using 1 swap. The minimum is 1.

Example 2:

Input: data = [0,0,0,1,0]
Output: 0
Explanation: Since there is only one 1 in the array, no swaps are needed.

Example 3:

Input: data = [1,0,1,0,1,0,0,1,1,0,1]
Output: 3
Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].

Constraints:

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

Explanation

Let count1 be the total number of 1s in data. In the final arrangement, all 1s must occupy one contiguous block of length count1, because there are exactly count1 ones to place.

So the problem becomes: among all windows of length count1, which window is best to turn into that block? A swap is only needed for each 0 inside the chosen window (swap it with a 1 outside), so we want the window with the fewest 0s, or equivalently the most 1s.

Use a fixed-size sliding window. Keep total as the number of 1s in the current window. Initialize it for the first count1 elements, then slide right by adding the new element and removing the element that left the window. For every window, required swaps are count1 - total. Track the minimum of this value.

This gives an O(n) solution with O(1) extra space.

Implementation

def minSwaps(self, data):
    count1 = data.count(1)
    total = 0
    for i in range(count1): total += data[i]
    swaps = count1-total
    for r in range(count1, len(data)):
        total += data[r]
        total -= data[r-count1]
        swaps = min(swaps, count1-total)
    return swaps

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

How does quick sort divide the problem into subproblems?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More