Minimum swaps to group all 1s together II

November 1, 2022

sliding-window

Problem URL: Minimum swaps to group all 1s together II

We will count number of ones in nums, let the number of ones be stored in the variable ones. Append nums to nums because we have to look at it as a circular array. Find the maximum number of ones in a window of size ones in the new array. Number of swaps = ones - maximum number of ones in a window of size ones.

class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        ones, n = nums.count(1), len(nums)
        x, onesInWindow = 0, 0
        for i in range(n * 2):
            if i >= ones and nums[i % n - ones]: 
                x -= 1
            if nums[i % n] == 1: 
                x += 1
            onesInWindow = max(x, onesInWindow)
        return ones - onesInWindow

Time complexity: O(n)
Space complexity: O(1)