Leetcode #2134: Minimum Swaps to Group All 1's Together II
In this guide, we solve Leetcode #2134 Minimum Swaps to Group All 1's Together II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
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:
[0,0,1,1,1,0,0] using 1 swap.
[0,1,1,1,0,0,0] using 1 swap.
[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).
There is no way to group all 1's together with 0 swaps.
Thus, the minimum number of swaps required is 1.
Python Solution
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
The time complexity is , where is the length of the array . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.