Minimum Swaps to Group All 1's Together II LeetCode solution in Python

1
class Solution:
2
def minSwaps(self, nums: List[int]) -> int:
3
width = sum(num == 1 for num in nums) # width of the window
4
nums += nums
5
res = width
6
curr_zeros = sum(
7
num == 0 for num in nums[:width]
8
) # the first window is nums[:width]
9

10
for i in range(width, len(nums)):
11
curr_zeros -= nums[i - width] == 0 # remove the leftmost 0 if exists
12
curr_zeros += nums[i] == 0 # add the rightmost 0 if exists
13
res = min(res, curr_zeros) # update if needed
14

15
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0