Minimum Swaps to Group All 1's Together II LeetCode

  Minimum Swaps to Group All 1's Together II


A swap is defined as taking two distinct positions in an array and swapping the values in them.


A circular array is defined as an array where we consider the first element and the last element to be adjacent.


Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.


 


Example 1:


Input: nums = [0,1,0,1,1,0,0]

Output: 1

Explanation: Here are a few of the ways to group all the 1's together:

[0,0,1,1,1,0,0] using 1 swap.

[0,1,1,1,0,0,0] using 1 swap.

[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).

There is no way to group all 1's together with 0 swaps.

Thus, the minimum number of swaps required is 1.

Example 2:


Input: nums = [0,1,1,1,0,0,1,1,0]

Output: 2

Explanation: Here are a few of the ways to group all the 1's together:

[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).

[1,1,1,1,1,0,0,0,0] using 2 swaps.

There is no way to group all 1's together with 0 or 1 swaps.

Thus, the minimum number of swaps required is 2.

Example 3:


Input: nums = [1,1,0,0,1]

Output: 0

Explanation: All the 1's are already grouped together due to the circular property of the array.

Thus, the minimum number of swaps required is 0.


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

        // Step 1: Count total 1s in the array (this determines the window size)
        int totalOnes = 0;
        for (int num : nums) {
            if (num == 1) {
                totalOnes++;
            }
        }

        // If there are no 1s or only 1s, no swaps are needed
        if (totalOnes == 0 || totalOnes == n) {
            return 0;
        }

        // Step 2: Count number of 0s in the first window of size `totalOnes`
        int bad = 0; // Count of '0's in the window (bad elements)
        for (int i = 0; i < totalOnes; i++) {
            if (nums[i] == 0) {
                bad++;
            }
        }

        // Step 3: Initialize minSwaps with the count of bad elements in the first window
        int minSwaps = bad;

        // Step 4: Slide the window across the circular array
        for (int i = 1; i < n; i++) {
            // Remove outgoing element from the left
            if (nums[(i - 1) % n] == 0) {
                bad--;
            }

            // Add incoming element from the right
            if (nums[(i + totalOnes - 1) % n] == 0) {
                bad++;
            }

            // Update minSwaps with the smallest bad count found
            minSwaps = Math.min(minSwaps, bad);
        }

        return minSwaps;
    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence