Minimum Swaps required to group all 1’s together
Easy Accuracy: 27.1% Submissions: 2105 Points: 2

Given an array of 0’s and 1’s, we need to write a program to find the minimum number of swaps required to group all 1’s present in the array together.

Input:
The first line consists of a single integer T, the number of test cases. For each test case, the first line contains an integer denoting the size of the array followed by
n space separated integers.

Output:
For each test case, the output is an integer displaying the minimum number of swaps required and if no 1's are present print -1.

Constraints:
1<=T<=100
1<=n<=50

Example:
Input
2
5
1 0 1 0 1
6
1 0 1 0 1 1
Output
1
1

Explanation:
1. Only 1 swap is required to group all 1's together. Swapping index 1 and 4 will give arr[] = {1, 1, 1, 0, 0}.
2. Only 1 swap is required. Swapping index 0 and 3 will give arr[]={0, 0, 1, 1, 1, 1}.

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.