Minimum Swaps required to group all 1’s together
Submissions: 1516   Accuracy:

25.38%

  Difficulty: Easy   Marks: 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}.

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Vanshika
Author: Vanshika_pec


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.