Skip to main content

Minimum Swaps to Group All 1's Together

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 204 ms)​

MetricValue
Runtime204 ms
Memory42.7 MB
Date2021-09-13
Solution
public class Solution {
public int MinSwaps(int[] data) {
int count = data.Where(x=> x==1).Count();
int left =0, right =0;
int curZeroes = 0;
int result = Int32.MaxValue;
while(right<data.Length)
{
if (data[right] == 0)
{
curZeroes++;
}
if(right-left+1>count)
{
if (data[left] == 0)
curZeroes--;
left++;
}
if(right-left+1==count)
{
result = Math.Min(result, curZeroes);


}
right++;
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed