Sliding Window with detailed Explanation | Beats 90% | TC: O(n)
IntuitionWe need to group all 1s together in a circular binary array while making the fewest swaps.

Since the array is circular, the first and last elements ar
# Intuition
We need to group all `1`s together in a circular binary array while making the fewest swaps.  

- Since the array is circular, the first and last elements are adjacent. Instead of treating it as a strict array, we can imagine extending it into a **linear form** by considering two copies of the array back-to-back.

- Our goal is to find a subarray (or window) of size equal to the total count of `1`s, which contains the **maximum number of `1`s** already grouped together.

- Once we find this window, the number of swaps required is simply the number of `0`s in this window, as those are the ones that need to be swapped.



# Approach

1. **Count the Total Number of `1`s (`totalOnes`)**  
   - Since all `1`s must be grouped together, the optimal window size should be `totalOnes`.

2. **Use a Sliding Window on a Virtual Extended Array**  
   - Since the array is circular, we extend it virtually using **modulo indexing**. This allows us to traverse the array efficiently without actually duplicating it.  
   - We maintain a **sliding window of size `totalOnes`**, keeping track of the number of `1`s in it.  

3. **Find the Window with Maximum `1`s**  
   - We move the window across the array and update the count dynamically.  
   - The best window is the one that contains the maximum number of `1`s, as it requires the fewest swaps.  

4. **Answer**  
   - The minimum swaps required is:  
   
     ```
     totalOnes - maxOnesInAWindow
     ```
   - This gives the number of `0`s that need to be swapped with `1`s to form a contiguous group.  



# Complexity
- Time complexity: $$O(n)$$

- Space complexity: $$O(1)$$

# Code
```java []
class Solution {
    public int minSwaps(int[] nums) {
        int totalOnes = 0;
        int n = nums.length;

        for(int i = 0; i < n; ++i) {
            totalOnes += nums[i];
        }

        if(totalOnes == 0) return 0;
        if(n < 2) return 0;

        int currWindowOnes = 0;
        int maxOnesTogether = 0;

        int end = 0, start = 0;

        while(start < n) {
            currWindowOnes += nums[end % n];


            if((end - start + 1) == totalOnes || 
                (start > end && Math.abs(end - start) == totalOnes)) {

                maxOnesTogether = Math.max(maxOnesTogether, currWindowOnes);

                if(nums[start] == 1) {
                    currWindowOnes--;
                }

                start++;
            }
            end++;
        }

        return totalOnes - maxOnesTogether;
    }
}
```
['Java']