You are given an array ‘arr’ of size ‘N’ containing 0 and 1. You can swap any two adjacent elements. Your task is to find the minimum number of swaps such that the 0 are shifted to one side, and 1 shifted to the other.
For example:For the given array ‘arr’ = {1,0,1,1} we can swap the first and second elements, and all 1s will be shifted to the right side and 0s to the left side. Hence a minimum number of operations required is 1.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows.
The first line of each test case contains an integer ‘N’, denoting the size of the array.
The second line of each test case contains ‘N’ space-separated integers representing the elements of the array.
Output Format :
For each test case, print the minimum number of swaps required to arrange 0 to one side and 1 to the other side.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N <= 10^6
0 <= arr[i] <= 1
Time limit: 1 sec
2
4
1 0 1 1
3
0 1 1
1
0
For test case 1 :
You can swap the first and second elements in order to shift all 1 to one side and 0 to the other.
For test case 2 :
In the given array, 0 and 1 are already on the opposite side. Hence no operations are required.
2
5
1 0 0 1 1
6
0 0 0 1 0 0
2
2
Try to find the minimum operation required to push all the 1s towards the left and right.
We will try to push all the 1s towards the left side.
After that, we will try to push all the 1s towards the right side.
The minimum number of swaps required in both cases will be our answer.
Algorithm :
O(N^2), where ‘N’ is the length of the array ‘arr’.
At each index, we are going back to count the number of 0s. Hence the overall time complexity is O(N^2).
O(N), where ‘N’ is the length of the array ‘arr’.
Since we have maintained a temporary array of size ‘N’, the overall space complexity is O(N).