Minimum Swaps to Group All 1's Together — LeetCode 1151 Python Solution

MediumLeetCode PremiumArraySliding Window
Problem
#1151
Reading time
2 min

The 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.

Example

Input
data = [1,0,1,0,1]
Output
1
Explanation
There are 3 ways to group all 1's together:

Python solution

Python
class Solution:
    def minSwaps(self, data: List[int]) -> int:
        k = data.count(1)
        mx = t = sum(data[:k])
        for i in range(k, len(data)):
            t += data[i]
            t -= data[i - k]
            mx = max(mx, t)
        return k - mx

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1151. Minimum Swaps to Group All 1's Together is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1151. Minimum Swaps to Group All 1's Together?
LeetCode 1151. Minimum Swaps to Group All 1's Together is rated Medium on LeetCode.
What is the time complexity of LeetCode 1151. Minimum Swaps to Group All 1's Together?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1151. Minimum Swaps to Group All 1's Together?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1151. Minimum Swaps to Group All 1's Together cover?
LeetCode 1151. Minimum Swaps to Group All 1's Together is tagged Array and Sliding Window on LeetCode.
Is LeetCode 1151. Minimum Swaps to Group All 1's Together a premium problem?
Yes. LeetCode 1151. Minimum Swaps to Group All 1's Together is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview