Minimum Swaps to Group 1s – Sliding Window Approach || Beginner Friendly || Beats 79.09 ||
Hey everyone! 👋I recently solved the "Minimum Swaps to Group 1s" problem using a sliding window approach on a circular array. Since the array is circular, I dup
Hey everyone! 👋  

I recently solved the "Minimum Swaps to Group 1s" problem using a **sliding window approach** on a **circular array**. Since the array is circular, I duplicated it to handle wrap-around cases efficiently.  

### 🔹 **Intuition**  
The goal is to minimize swaps needed to bring all `1`s together in a contiguous subarray. We can treat it like a **fixed-size sliding window**, where the window size is equal to the total number of `1`s in the array.  

### 🔹 **Approach**  
1. **Count the total number of `1`s** in the array. This gives us our ideal window size.  
2. **Duplicate the array** to simulate circular behavior.  
3. **Use a sliding window** to track the number of `1`s in the window and compute the minimum swaps needed.  

### 🔹 **Complexity Analysis**  
- **Time Complexity:** $$O(n)$$ – Since we iterate over the array twice (once to count `1`s, once to slide the window).  
- **Space Complexity:** $$O(n)$$ – Due to array duplication.  

### 🔹 **Code (Java)**
```java
class Solution {
    public int minSwaps(int[] nums) {
        int n = nums.length;
        int[] arr = new int[2*n];
        int ones = 0;
        
        for(int i = 0; i < n; i++ ) {
            ones += nums[i];
        }
        
        for(int i = 0; i < 2*n; i++) {
            arr[i] = nums[i % n];
        }

        int cur_one = 0;
        for(int i = 0; i < ones; i++) {
            cur_one += arr[i];
        }
        
        int min_swap = Integer.MAX_VALUE;
        
        for(int i = ones; i < 2*n; i++) {
            cur_one -= arr[i - ones];
            cur_one += arr[i];
            min_swap = Math.min(min_swap, ones - cur_one);
        }
        
        return min_swap;
    }
}
```

### 💡 **Final Thoughts**  
I found that **sliding window** was the best approach to minimize swaps efficiently.  
Would love to hear your feedback! Did anyone take a different approach? 👀  



['Java']