Minimum Swaps required to group all 1’s together

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.

Examples:

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

Input : arr[] = {1, 0, 1, 0, 1, 1}
Output : 1



A simple solution is to first count total number of 1’s in the array. Suppose this count is x, now we need to find the subarray of length x of this array with maximum number of 1’s. And minimum swaps required will be the number of 0’s in the subarray of length x with maximum number of 1’s.
Time Complexity: O(n2)

An efficient solution is to optimize the brute force technique of finding the subarray in above approach using the concept of sliding window technique. We can maintain a preCount array to find number of 1’s present in a subarray in O(1) time complexity.

Below is the implementation of above idea:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find minimum swaps
// required to group all 1's together
#include <iostream>
#include <limits.h>
  
using namespace std;
  
// Function to find minimum swaps
// to group all 1's together
int minSwaps(int arr[], int n) {
  
  int noOfOnes = 0;
  
  // find total number of all in the array
  for (int i = 0; i < n; i++) {
    if (arr[i] == 1)
      noOfOnes++;
  }
  
  // length of subarray to check for
  int x = noOfOnes;
  
  int maxOnes = INT_MIN;
  
  // array to store number of 1's upto
  // ith index
  int preCompute[n] = {0};
  
  // calculate number of 1's upto ith
  // index and store in the array preCompute[]
  if (arr[0] == 1)
    preCompute[0] = 1;
  for (int i = 1; i < n; i++) {
    if (arr[i] == 1) {
      preCompute[i] = preCompute[i - 1] + 1;
    } else
      preCompute[i] = preCompute[i - 1];
  }
  
  // using sliding window technique to find
  // max number of ones in subarray of length x
  for (int i = x - 1; i < n; i++) {
    if (i == (x - 1)) 
      noOfOnes = preCompute[i];
    else 
      noOfOnes = preCompute[i] - preCompute[i - x];
      
    if (maxOnes < noOfOnes)
      maxOnes = noOfOnes;
  }
  
  // calculate number of zeros in subarray
  // of length x with maximum number of 1's
  int noOfZeroes = x - maxOnes;
  
  return noOfZeroes;
}
  
// Driver Code
int main() {
  int a[] = {1, 0, 1, 0, 1};
  int n = sizeof(a) / sizeof(a[0]);
  cout << minSwaps(a, n);
  return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java  program to find minimum swaps
// required to group all 1's together
  
import java.io.*;
  
class GFG {
  
// Function to find minimum swaps
// to group all 1's together
 static int minSwaps(int arr[], int n) {
  
int noOfOnes = 0;
  
// find total number of all in the array
for (int i = 0; i < n; i++) {
    if (arr[i] == 1)
    noOfOnes++;
}
  
// length of subarray to check for
int x = noOfOnes;
  
int maxOnes = Integer.MIN_VALUE;
  
// array to store number of 1's upto
// ith index
int preCompute[] = new int[n];
  
// calculate number of 1's upto ith
// index and store in the array preCompute[]
if (arr[0] == 1)
    preCompute[0] = 1;
for (int i = 1; i < n; i++) {
    if (arr[i] == 1) {
    preCompute[i] = preCompute[i - 1] + 1;
    } else
    preCompute[i] = preCompute[i - 1];
}
  
// using sliding window technique to find
// max number of ones in subarray of length x
for (int i = x - 1; i < n; i++) {
    if (i == (x - 1)) 
    noOfOnes = preCompute[i];
    else
    noOfOnes = preCompute[i] - preCompute[i - x];
      
    if (maxOnes < noOfOnes)
    maxOnes = noOfOnes;
}
  
// calculate number of zeros in subarray
// of length x with maximum number of 1's
int noOfZeroes = x - maxOnes;
  
return noOfZeroes;
}
  
// Driver Code
public static void main (String[] args) {
int a[] = {1, 0, 1, 0, 1};
int n = a.length;
System.out.println( minSwaps(a, n));
      
    }
}
  
// This code is contributed by vt_m.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to
# find minimum swaps
# required to group
# all 1's together
  
# Function to find minimum swaps
# to group all 1's together
def minSwaps(arr,n):
      
    noOfOnes = 0
   
    # find total number of
    # all in the array
    for i in range(n):
        if (arr[i] == 1):
            noOfOnes=noOfOnes+1
    
   
    # length of subarray to check for
    x = noOfOnes
   
    maxOnes = -2147483648
   
    # array to store number of 1's upto
    # ith index
    preCompute={}
   
    # calculate number of 1's upto ith
    # index and store in the
    # array preCompute[]
    if (arr[0] == 1):
        preCompute[0] = 1
    for i in range(1,n):
        if (arr[i] == 1):
            preCompute[i] = preCompute[i - 1] + 1
        else:
            preCompute[i] = preCompute[i - 1]
    
   
    # using sliding window
    # technique to find
    # max number of ones in
    # subarray of length x
    for i in range(x-1,n):
        if (i == (x - 1)): 
            noOfOnes = preCompute[i]
        else:
            noOfOnes = preCompute[i] - preCompute[i - x]
       
        if (maxOnes < noOfOnes):
            maxOnes = noOfOnes
    
   
    # calculate number of zeros in subarray
    # of length x with maximum number of 1's
    noOfZeroes = x - maxOnes
   
    return noOfZeroes
    
# Driver code
  
a = [1, 0, 1, 0, 1]
n = len(a)
  
print(minSwaps(a, n))
  
# This code is contributed
# by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find minimum swaps
// required to group all 1's together
  
using System;
  
class GFG {
  
    // Function to find minimum swaps
    // to group all 1's together
    static int minSwaps(int []arr, int n) {
      
        int noOfOnes = 0;
          
        // find total number of all in the array
        for (int i = 0; i < n; i++) {
            if (arr[i] == 1)
            noOfOnes++;
        }
          
        // length of subarray to check for
        int x = noOfOnes;
          
        int maxOnes = int.MinValue;
          
        // array to store number of 1's upto
        // ith index
        int []preCompute = new int[n];
          
        // calculate number of 1's upto ith
        // index and store in the array preCompute[]
        if (arr[0] == 1)
            preCompute[0] = 1;
        for (int i = 1; i < n; i++) {
            if (arr[i] == 1) {
            preCompute[i] = preCompute[i - 1] + 1;
            } else
            preCompute[i] = preCompute[i - 1];
        }
          
        // using sliding window technique to find
        // max number of ones in subarray of length x
        for (int i = x - 1; i < n; i++) {
            if (i == (x - 1)) 
            noOfOnes = preCompute[i];
            else
            noOfOnes = preCompute[i] - preCompute[i - x];
              
            if (maxOnes < noOfOnes)
            maxOnes = noOfOnes;
        }
          
        // calculate number of zeros in subarray
        // of length x with maximum number of 1's
        int noOfZeroes = x - maxOnes;
          
        return noOfZeroes;
    }
      
    // Driver Code
    public static void Main () 
    {
        int []a = {1, 0, 1, 0, 1};
        int n = a.Length;
        Console.WriteLine( minSwaps(a, n));
          
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find minimum swaps
// required to group all 1's together
  
// Function to find minimum swaps
// to group all 1's together
function minSwaps($arr, $n
{
  
        $noOfOnes = 0;
          
        // find total number of 
        // all in the array
        for($i = 0; $i < $n; $i++) 
        {
            if ($arr[$i] == 1)
            $noOfOnes++;
        }
          
        // length of subarray 
        // to check for
        $x = $noOfOnes;
          
        $maxOnes = PHP_INT_MIN;
          
        // array to store number of 
        // 1's upto ith index
        $preCompute = array();
          
        // calculate number of 1's 
        // upto ith index and store
        // in the array preCompute[]
        if ($arr[0] == 1)
            $preCompute[0] = 1;
        for($i = 1; $i < $n; $i++) 
        {
            if ($arr[$i] == 1)
            {
                $preCompute[$i] = $preCompute[$i - 1] + 1;
            
            else
                $preCompute[$i] = $preCompute[$i - 1];
        }
          
        // using sliding window 
        // technique to find
        // max number of ones in
        // subarray of length x
        for ( $i = $x - 1; $i < $n; $i++)
        {
            if ($i == ($x - 1)) 
                $noOfOnes = $preCompute[$i];
            else
                $noOfOnes = $preCompute[$i] - 
                            $preCompute[$i - $x];
              
            if ($maxOnes < $noOfOnes)
                $maxOnes = $noOfOnes;
        }
          
        // calculate number of zeros in subarray
        // of length x with maximum number of 1's
        $noOfZeroes = $x - $maxOnes;
          
        return $noOfZeroes;
}
  
// Driver Code
$a = array(1, 0, 1, 0, 10);
$n = count($a);
echo minSwaps($a, $n);
  
// This code is contributed by anuj_67.
?>

chevron_right


Output:

1

Time Complexity: O(n)
Auxiliary Space: O(n)

Another efficient approach :
First count total number of 1’s in the array. Suppose this count is x, now find the subarray of length x of this array with maximum number of 1’s using the concept of window-sliding technique. Maintain a variable to find number of 1’s present in a subarray in O(1) extra space and for each sub array maintain maxOnes Variable and at last Return numberOfZeros (numberOfZeroes = x – maxOnes).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for minimum swaps
// required to group all 1's together
#include <iostream>
#include <limits.h>
  
using namespace std;
  
// Function to find minimum swaps
// to group all 1's together
int minSwaps(int arr[], int n)
{
  
int numberOfOnes = 0;
  
// find total number of all 1's in the array
for (int i = 0; i < n; i++) {
    if (arr[i] == 1)
    numberOfOnes++;
}
  
// length of subarray to check for
int x = numberOfOnes;
  
int count_ones = 0, maxOnes;
  
// Find 1's for first subarray of length x
for(int i = 0; i < x; i++){
    if(arr[i] == 1)
    count_ones++;
}
      
maxOnes = count_ones;
      
// using sliding window technique to find
// max number of ones in subarray of length x
for (int i = 1; i <= n-x; i++) {
      
    // first remove leading element and check
    // if it is equal to 1 then decreament the 
    // value of count_ones by 1
    if (arr[i-1] == 1) 
    count_ones--;
      
    // Now add trailing element and check
    // if it is equal to 1 Then increament 
    // the value of count_ones by 1
    if(arr[i+x-1] == 1)
    count_ones++;
      
    if (maxOnes < count_ones)
    maxOnes = count_ones;
}
  
// calculate number of zeros in subarray
// of length x with maximum number of 1's
int numberOfZeroes = x - maxOnes;
  
return numberOfZeroes;
}
  
// Driver Code
int main() {
      
int a[] = {0, 0, 1, 0, 1, 1, 0, 0, 1};
int n = sizeof(a) / sizeof(a[0]);
  
cout << minSwaps(a, n);
  
return 0;
  
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// java program to find largest number
// smaller than equal to n with m set
// bits then m-1 0 bits.
public class GFG {
      
    // Function to find minimum swaps
    // to group all 1's together
    static int minSwaps(int arr[], int n)
    {
      
        int numberOfOnes = 0;
          
        // find total number of all 1's
        // in the array
        for (int i = 0; i < n; i++) {
            if (arr[i] == 1)
                numberOfOnes++;
        }
          
        // length of subarray to check for
        int x = numberOfOnes;
          
        int count_ones = 0, maxOnes;
          
        // Find 1's for first subarray
        // of length x
        for(int i = 0; i < x; i++){
            if(arr[i] == 1)
                count_ones++;
        }
              
        maxOnes = count_ones;
              
        // using sliding window technique 
        // to find max number of ones in
        // subarray of length x
        for (int i = 1; i <= n-x; i++) {
              
            // first remove leading element 
            // and check if it is equal to
            // 1 then decreament the 
            // value of count_ones by 1
            if (arr[i - 1] == 1
                count_ones--;
              
            // Now add trailing element 
            // and check if it is equal 
            // to 1 Then increament the
            // value of count_ones by 1
            if(arr[i + x - 1] == 1)
                count_ones++;
              
            if (maxOnes < count_ones)
            maxOnes = count_ones;
        }
          
        // calculate number of zeros in
        // subarray of length x with
        // maximum number of 1's
        int numberOfZeroes = x - maxOnes;
          
        return numberOfZeroes;
    }
      
    // Driver code
    public static void main(String args[]) 
    {
        int a[] = new int[]{0, 0, 1, 0
                            1, 1, 0, 0, 1};
        int n = a.length;
          
        System.out.println(minSwaps(a, n));
    }
}
  
// This code is contributed by Sam007

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code for minimum 
# swaps required to group 
# all 1's together
  
# Function to find minimum 
# swaps to group all 1's
# together
def minSwaps(arr, n) :
  
    numberOfOnes = 0
      
    # find total number of 
    # all 1's in the array
    for i in range(0, n) :
  
        if (arr[i] == 1) :
            numberOfOnes = numberOfOnes + 1
      
    # length of subarray
    # to check for
    x = numberOfOnes
      
    count_ones = 0
    maxOnes = 0
      
    # Find 1's for first 
    # subarray of length x
    for i in range(0, x) :
  
        if(arr[i] == 1) :
            count_ones = count_ones + 1
          
    maxOnes = count_ones
          
    # using sliding window 
    # technique to find
    # max number of ones in
    # subarray of length x
    for i in range(1, (n - x + 1)) :
          
        # first remove leading
        # element and check
        # if it is equal to 1 
        # then decreament the 
        # value of count_ones by 1
        if (arr[i - 1] == 1) : 
            count_ones = count_ones - 1
          
        # Now add trailing 
        # element and check
        # if it is equal to 1 
        # Then increament 
        # the value of count_ones by 1
        if(arr[i + x - 1] == 1) :
            count_ones = count_ones + 1
          
        if (maxOnes < count_ones) :
                maxOnes = count_ones
      
    # calculate number of 
    # zeros in subarray
    # of length x with 
    # maximum number of 1's
    numberOfZeroes = x - maxOnes
      
    return numberOfZeroes
  
# Driver Code
a = [0, 0, 1, 0, 1, 1, 0, 0, 1]
n = 9
print (minSwaps(a, n)) 
  
# This code is contributed 
# by Manish Shaw(manishshaw1)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code for minimum swaps
// required to group all 1's together
using System;
  
class GFG{
      
    // Function to find minimum swaps
    // to group all 1's together
    static int minSwaps(int []arr, int n)
    {
      
        int numberOfOnes = 0;
          
        // find total number of all 1's in the array
        for (int i = 0; i < n; i++) {
            if (arr[i] == 1)
            numberOfOnes++;
        }
          
        // length of subarray to check for
        int x = numberOfOnes;
          
        int count_ones = 0, maxOnes;
          
        // Find 1's for first subarray of length x
        for(int i = 0; i < x; i++){
            if(arr[i] == 1)
            count_ones++;
        }
              
        maxOnes = count_ones;
              
        // using sliding window technique to find
        // max number of ones in subarray of length x
        for (int i = 1; i <= n-x; i++) {
              
            // first remove leading element and check
            // if it is equal to 1 then decreament the 
            // value of count_ones by 1
            if (arr[i - 1] == 1) 
            count_ones--;
              
            // Now add trailing element and check
            // if it is equal to 1 Then increament 
            // the value of count_ones by 1
            if(arr[i + x - 1] == 1)
            count_ones++;
              
            if (maxOnes < count_ones)
            maxOnes = count_ones;
        }
          
        // calculate number of zeros in subarray
        // of length x with maximum number of 1's
        int numberOfZeroes = x - maxOnes;
          
        return numberOfZeroes;
    }
      
    // Driver Code
    static public void Main ()
    {
        int []a = {0, 0, 1, 0, 1, 1, 0, 0, 1};
        int n = a.Length;
      
        Console.WriteLine(minSwaps(a, n));
          
    }
}
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP code for minimum swaps
// required to group all 1's together
  
// Function to find minimum swaps
// to group all 1's together
function minSwaps($arr, $n)
{
  
    $numberOfOnes = 0;
      
    // find total number of 
    // all 1's in the array
    for ($i = 0; $i < $n; $i++) 
    {
        if ($arr[$i] == 1)
            $numberOfOnes++;
    }
      
    // length of subarray to check for
    $x = $numberOfOnes;
      
    $count_ones = 0;
    $maxOnes;
      
    // Find 1's for first 
    // subarray of length x
    for($i = 0; $i < $x; $i++)
    {
        if($arr[$i] == 1)
            $count_ones++;
    }
          
    $maxOnes = $count_ones;
          
    // using sliding window 
    // technique to find
    // max number of ones in
    // subarray of length x
    for ($i = 1; $i <= $n - $x; $i++) 
    {
          
        // first remove leading
        // element and check
        // if it is equal to 1 
        // then decreament the 
        // value of count_ones by 1
        if ($arr[$i - 1] === 1) 
            $count_ones--;
          
        // Now add trailing 
        // element and check
        // if it is equal to 1 
        // Then increament 
        // the value of count_ones by 1
        if($arr[$i + $x - 1] === 1)
                $count_ones++;
          
        if ($maxOnes < $count_ones)
                $maxOnes = $count_ones;
    }
      
    // calculate number of zeros in subarray
    // of length x with maximum number of 1's
    $numberOfZeroes = $x - $maxOnes;
      
    return $numberOfZeroes;
}
  
// Driver Code
$a = array(0, 0, 1, 0, 1, 1, 0, 0, 1);
$n = 9;
echo minSwaps($a, $n);
  
// This code is contributed by Anuj_67
?>

chevron_right



Output:

1

Time Complexity : O(n)
Auxiliary Space : O(1)

Thanks to Mr. Gera for suggesting this approach.



My Personal Notes arrow_drop_up

Senior Technical Content Engineer | GeeksforGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Sam007, vt_m, manishshaw1