430. Minimum Swaps to Group All 1’s Together

There is a binary array data of length n, where each element is either 0 or 1. In one move, you can swap any two elements of the array. Your task is to determine the minimum number of swaps required so that all the 1’s in the array become grouped together (i.e. appear consecutively). If the 1’s are already grouped together, return 0.

Return the minimum number of swaps required.

Example 1:

Input: data = [1, 0, 1, 0, 1]

Output: 1

Explanation: There are 3 ones in the array. If you consider a window of length 3, the optimal window (either the first or last window) contains 2 ones. Thus, the minimum swaps required = 3 - 2 = 1.

Example 2:

Input: data = [1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1]

Output: 3

Explanation: One possible solution that uses 3 swaps is [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1].

Now Your Turn!

Pick the correct output for the given input

Input: data = [0, 1, 1, 0, 1, 0, 0, 1, 1, 0]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

1 <= data.length <= 105

data[i] is either 0 or 1.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int minSwaps(vector<int>& data) {
// Your Code Goes Here
}
};
Test Case

Input:

Data