Given a binary array, find the number of minimum adjacent swaps needed to group 1's and 0's.
Example:
Input : 0,1,0,1 (array with 0 based index)
Swaps needed : 0,1,0,1 -> 0,0,1,1 (1 swap from index 1 to index 2)
Solution : 1
Exmaple:
Input : 1,0,1,0,0,0,0,1
Swaps needed :
1,0,1,0,0,0,0,1 -> 1,1,0,0,0,0,0,1 -> 1,1,0,0,0,0,1,0 -> 1,1,0,0,0,1,0,0 -> 1,1,0,0,1,0,0,0 -> 1,1,0,1,0,0,0,0 -> 1,1,1,0,0,0,0,0
Total 6 swaps so the solution is 6.
The 1's and 0's can be positioned at the beginning or end but they should be at a single place i.e. either begin or end.
I have come up with below logic for this requirement. I tried this in a hackerrank, it failed for a single hidden test case and gave timeout for 3 test cases as I have nested loops in my code.
static int countSwaps(List<Integer> list) {
int temp;
int swaps = 0;
int n = list.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if ((list.get(j) == 0) && (list.get(j + 1) == 1)) {
temp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, temp);
swaps++;
}
}
}
return swaps;
}
What is a better approach to solving this program?
I have already gone through this post Given an array of 0 and 1, find minimum no. of swaps to bring all 1s together (only adjacent swaps allowed) but the answers are not giving correct output.
Sort Binary array, so it always tries to place 0 at first place. But in my case, the first place can be occupied by 0 or 1