1151. Minimum Swaps to Group All 1's Together
Description
Given a binary array data
, return the minimum number of swaps required to group all 1
’s present in the array together in any place in the array.
Constraints
1 <= data.length <= 105
data[i]
is0
or1
.
Approach
Links
GeeksforGeeks
ProgramCreek
Examples
Input: data = [1, 0, 1, 0, 1]
Output: 1
Explanation:
There are 3 ways to group all 1's together:
[1, 1, 1, 0, 0] using 1 swap.
[0, 1, 1, 1, 0] using 2 swaps.
[0, 0, 1, 1, 1] using 1 swap.
The minimum is 1.
Solutions
/**
* Time complexity : O(n), when n is the length of the array.
* Space complexity : O(1)
*/
class Solution {
public int minSwaps(int[] data) {
if(data == null || data.length <= 2) {
return 0;
}
int numOf1 = 0;
for(int i = 0; i < data.length; i++) {
if(data[i] == 1) {
numOf1++;
}
}
int currOne = 0;
for(int i = 0; i < numOf1; i++) {
if(data[i] == 1) {
currOne++;
}
}
int result = numOf1-currOne;
for(int i = 1; i <= data.length-numOf1; i++) {
if(data[i-1] == 1) {
currOne--;
}
if(data[i + numOf1 - 1] == 1) {
currOne++;
}
result = Math.min(result, numOf1-currOne);
}
return result;
}
}
Follow up
Last updated
Was this helpful?