Minimum Swaps to Group All 1's Together II LeetCode solution in Python
1class Solution:2def minSwaps(self, nums: List[int]) -> int:3width = sum(num == 1 for num in nums) # width of the window4nums += nums5res = width6curr_zeros = sum(7num == 0 for num in nums[:width]8) # the first window is nums[:width]910for i in range(width, len(nums)):11curr_zeros -= nums[i - width] == 0 # remove the leftmost 0 if exists12curr_zeros += nums[i] == 0 # add the rightmost 0 if exists13res = min(res, curr_zeros) # update if needed1415return res