Easiest Explanation You Will Find
Approach\nIf you have premium account, solve this problem first: 1151. Minimum Swaps to Group All 1\'s Together. This is a similar problem where the array is no
# Approach\nIf you have premium account, solve this problem first: [1151. Minimum Swaps to Group All 1\'s Together](https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together/). This is a similar problem where the array is not circular.\n\nTo solve that problem you will use a basic sliding window technique:\n\n``` java []\npublic int minSwaps(int[] data) {\n    int window=Arrays.stream(data).sum();\n    int maxOnesInWindow=0;\n    int onesInCurWindow=0;\n    for(int right=0; right<data.length; right++) {\n        onesInCurWindow+=data[right];\n        if(right > window-1) {\n            onesInCurWindow-=data[right-window];\n        }\n        maxOnesInWindow = Math.max(maxOnesInWindow, onesInCurWindow);\n    }\n    return window - maxOnesInWindow;\n}\n```\nFor circular array, we will use this same function. The circular property of the array opens up more possible groupings to consider compared to a linear array. So, we will also need to consider **zeroGroups**. When zeroes are grouped, ones are also grouped. And when we swap a zero, we will swap it with a one. So, here\'s the solution:\n\n# Code\n``` Java []\nclass Solution {\n    public int minSwaps(int[] nums) {\n        int ones = Arrays.stream(nums).sum();\n        // swaps required to group zeroes\n        // if zeroes are grouped, so are the ones...\n        int zeroGroups = slidingWindow(nums, 0, nums.length-ones);\n        // swaps required to group ones\n        int oneGroups = slidingWindow(nums, 1, ones);\n        // minimum swaps required\n        return Math.min(zeroGroups, oneGroups);\n    }\n\n    int slidingWindow(int[] nums, int val, int window) {\n        int valsInWindow = 0;\n        int maxValsInWindow = 0;\n        for(int i=0; i<nums.length; i++) {\n            // our val can be 0 or 1\n            // if current number matches val, then increment valsInWindow\n            valsInWindow += (nums[i] == val? 1: 0);\n            if(i>window-1) {\n                // let windowIndexBfrStart = i-window,\n                // if the value in nums[windowIndexBfrStart] == val,\n                // decrement it from valsInWindow\n                valsInWindow -= (nums[i-window]==val? 1 : 0);\n            }\n            maxValsInWindow = Math.max(maxValsInWindow, valsInWindow);\n        }\n        return window - maxValsInWindow;\n    }\n}\n```\n\n\n# Complexity\n- Time complexity: $$O(n)$$\nEach time traversing the loop only once. So, total $2n = n$ loop traversals.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\nNo extra array, map or any other datastructure.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n
['Array', 'Sliding Window', 'Java']