MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / minSwaps

Method minSwaps

minimumSwapsToGroup1sTogether.java:2–34  ·  view source on GitHub ↗
(int[] nums)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int minSwaps(int[] nums) {
3 //window size - count of 1
4 int windowSize = 0;
5 for(int num : nums){
6 windowSize+=num;
7 }
8 //find zeros in first window
9 int curZeros=0;
10 for(int i=0;i<windowSize;i++){
11 if(nums[i]==0){
12 curZeros++;
13 }
14 }
15 //solve for remaining window
16 int minZeros = curZeros;
17 int start=0;
18 int end = windowSize-1;
19 int n = nums.length;
20 while(start<n){
21 //if removed element was 0, decrement 0 counter
22 if(nums[start]==0){
23 curZeros--;
24 }
25 start++;
26 // if included element is 0, increment 0 counter
27 end++;
28 if(nums[end%n]==0){
29 curZeros++;
30 }
31 minZeros = Math.min(minZeros, curZeros);
32 }
33 return minZeros;
34 }
35}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected