Minimum Swaps to Group All 1’s Together

Asked atSwiggy
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

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.

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.

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

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

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

cpp

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

java

class Solution {
    public int minSwaps(int[] data) {
        // Your Code Goes Here
    }
}

python

class Solution(object):
    def minSwaps(self, data):
        """
        :type data: List[int]
        :rtype: int
        """
        // Your Code Goes Here

javascript

/**
 * @param {number[]} data
 * @return {number}
 */
var minSwaps = function(data) {
    //Your Code Goes Here
};

csharp

class Solution
{
    public int minSwaps(int[] data)
    {
        // Your Code Goes Here
    }
}

go

func minSwaps(data []int) int {
	// Your code goes here
}
Stuck? Show a way to structure it+
  1. 01Count total ones to get window length k.
  2. 02Count ones in the first k positions.
  3. 03Slide the window one step at a time.
  4. 04Keep the maximum ones in any k window.
  5. 05Return k minus that maximum.

Reference answer

Then expect these follow-ups

  • How does the circular variant change?

    Tests: modular indexing

  • Can you return the best block boundaries?

    Tests: tracking

Hiring now

Swiggy has 152 open roles right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Content Lead

    Mumbai, MH, India

  • Sales Manager I

    Kolhapur, MH, India

  • Assistant Manager- Finance

    Bengaluru, KA, India

Or practice this question first

Next question