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

MediumArraySliding Window
Problem
#2134
Reading time
2 min

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

Example

Input
nums = [0,1,0,1,1,0,0]
Output
1
Explanation
Here are a few of the ways to group all the 1's together:

Python solution

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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2134. Minimum Swaps to Group All 1's Together II 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 2134. Minimum Swaps to Group All 1's Together II?
LeetCode 2134. Minimum Swaps to Group All 1's Together II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2134. Minimum Swaps to Group All 1's Together II?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2134. Minimum Swaps to Group All 1's Together II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2134. Minimum Swaps to Group All 1's Together II cover?
LeetCode 2134. Minimum Swaps to Group All 1's Together II is tagged Array and Sliding Window on LeetCode.

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