2134. Minimum Swaps to Group All 1's Together II

T: O(n)

S: O(n)

class Solution {
    public int minSwaps(int[] nums) {
        int n = nums.length;

        int winSize = 0; // all 1's togeter will be the window size
        
        // for circular array, just need " append another same array " on the original array
        int[] data = new int[2*n]; 
        for (int i = 0; i < n; i++) {
            if (nums[i] == 1) {
                winSize++;
            }
            data[i] = nums[i];
            data[i+n] = nums[i];
        }
        
        int left = 0;
        int oneCount = 0; // count in this window, how many one
        int res = winSize;
        
        for (int right = 0; right < data.length; right++) {
            if (right - left + 1 > winSize) {
                oneCount -= data[left++];
            }
            oneCount += data[right];
            
            if (right - left + 1 == winSize) {
                // 0 needs to swap = winSize(total of ones) - one's count in window
                res = Math.min(res, winSize - oneCount); 
            }
        }
        return res;
        
    }
}

Last updated