Skip to content

Latest commit

 

History

History

1151

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

 

Example 1:

Input: data = [1,0,1,0,1]
Output: 1
Explanation: There are 3 ways to group all 1's together:
[1,1,1,0,0] using 1 swap.
[0,1,1,1,0] using 2 swaps.
[0,0,1,1,1] using 1 swap.
The minimum is 1.

Example 2:

Input: data = [0,0,0,1,0]
Output: 0
Explanation: Since there is only one 1 in the array, no swaps are needed.

Example 3:

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].

 

Constraints:

  • 1 <= data.length <= 105
  • data[i] is either 0 or 1.

Companies: Amazon, Uber, Expedia

Related Topics:
Array, Sliding Window

Similar Questions:

Solution 1. Fixed-length Sliding Window

// OJ: https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int minSwaps(vector<int>& A) {
        int total = accumulate(begin(A), end(A), 0), N = A.size(), one = 0, ans = N;
        for (int i = 0; i < N; ++i) {
            one += A[i];
            if (i - total >= 0) one -= A[i - total];
            ans = min(ans, total - one);
        }
        return ans;
    }
};