Minimum Swaps to Group All 1's Together II — LeetCode 2134 Python Solution
- Problem
- #2134
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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
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 - mxComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(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.