1151. Minimum Swaps to Group All 1's Together

  • Number of swaps = totalones - maximum number of ones in a window of size ones

T: O(n)
S: O(1)
class Solution {
    public int minSwaps(int[] data) {
        int n = data.length;
        int winSize = 0;
        for (int num : data) {
            if (num == 1) {
                winSize++;
            }
        }
        
        int oneCount = 0;
        int left = 0;
        int res = winSize;
        
        for (int right = 0; right < n; right++) {
            if (right - left + 1 > winSize) {
                oneCount -= data[left++];
            }
            oneCount += data[right];
            
            if (right - left + 1 == winSize) {
                res = Math.min(res, winSize - oneCount);
            }
        }
        return res;
    }
}
/*
min swap = total of one's count(win size) - one's count in this sliding window
 0 1 2
[1,0,1,0,1]
[     ]

T: O(n)
S: O(1)
*/

or count 0

Last updated

Was this helpful?