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++
// 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; } |
Java
// 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. |
Python3
# 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. |
C#
// 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. |
PHP
<?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. ?> |
Javascript
<script> // Javascript 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) { let noOfOnes = 0; // find total number of all in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for let x = noOfOnes; let maxOnes = Number.MIN_VALUE; // array to store number of 1's upto // ith index let preCompute = new Array(n); preCompute.fill(0); // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (let 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 (let 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 let noOfZeroes = x - maxOnes; return noOfZeroes; } let a = [1, 0, 1, 0, 1]; let n = a.length; document.write( minSwaps(a, n)); </script> |
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).
Implementation:
C++
// 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 decrement 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 increment // 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; } |
Java
// 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 decrement 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 increment 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 |
Python3
# 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 decrement 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 increment # 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) |
C#
// 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 decrement 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 increment // 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. |
PHP
<?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 decrement 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 increment // 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 ?> |
Javascript
<script> // Javascript 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) { let numberOfOnes = 0; // find total number of all 1's in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for let x = numberOfOnes; let count_ones = 0, maxOnes; // Find 1's for first subarray of length x for (let 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 (let i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement 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 increment // 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 let numberOfZeroes = x - maxOnes; return numberOfZeroes; } let a = [0, 0, 1, 0, 1, 1, 0, 0, 1]; let n = a.length; document.write(minSwaps(a, n)); </script> |
1
Time Complexity : O(n)
Auxiliary Space : O(1)
Thanks to Mr. Gera for suggesting this approach.
Sliding window Easy to understand version
Algorithm:
- Store the total no of ones in a variable say count. This will be the window size.
- Initialise a variable to store maximum no of ones out of all the sub arrays of size count and a variable to store count of ones in current window.
- Now iterate over the array and as soon as you hit the window size compare the no of ones in that window with the maximum count of ones in all the windows so far and update max count of ones if count of ones in the current window is more. If the first element of window is 1 then decrease the current count.
- Answer will be total count of ones – max count of ones out of all window.
Implementation:
C++
#include <bits/stdc++.h> using namespace std; int minSwaps( int arr[], int n) { int totalCount = 0; // To store total number of ones // count total no of ones for ( int i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out of all windows int i = 0; // start of window int j = 0; // end of window while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1) == totalCount) { maxCount = max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count if first element of window is 1 i++; // slide window } j++; } return totalCount - maxCount; // return total no of ones in array - maximum count of ones out of all windows } // Driver Code int main() { int a[] = {1, 0, 1, 0, 1, 1}; int n = sizeof (a) / sizeof (a[0]); cout << minSwaps(a, n); return 0; } |
Java
import java.io.*; import java.util.*; class GFG{ static int minSwaps( int [] arr, int n) { // To store total number of ones int totalCount = 0 ; // Count total no of ones int i; for (i = 0 ; i < n; i++) totalCount += arr[i]; int currCount = 0 ; // To store count of ones in current window int maxCount = 0 ; // To store maximum count ones out // of all windows // start of window i = 0 ; // end of window int j = 0 ; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1 ) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1 ) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows } // Driver Code public static void main(String args[]) { int [] a = { 1 , 0 , 1 , 0 , 1 , 1 }; int n = a.length; System.out.println(minSwaps(a, n)); } } // This code is contributed by shivanisinghss2110 |
Python
def minSwaps(arr, n): # To store total number of ones totalCount = 0 # count total no of ones for i in range ( 0 ,n): totalCount + = arr[i] currCount = 0 # To store count of ones in current window maxCount = 0 # To store maximum count ones out of all windows i = 0 # start of window j = 0 # end of window while (j < n): currCount + = arr[j] # update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1 ) = = totalCount): maxCount = max (maxCount, currCount) if (arr[i] = = 1 ): currCount - = 1 # decrease current count if first element of window is 1 i + = 1 # slide window j + = 1 return totalCount - maxCount # return total no of ones in array - maximum count of ones out of all windows # Driver Code a = [ 1 , 0 , 1 , 0 , 1 , 1 ] n = len (a) print (minSwaps(a, n)) # this code is contributed by shivanisighss2110 |
C#
using System; class GFG{ static int minSwaps( int [] arr, int n) { // To store total number of ones int totalCount = 0; // Count total no of ones int i; for (i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window int j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.Max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows } // Driver Code public static void Main() { int [] a = { 1, 0, 1, 0, 1, 1 }; int n = a.Length; Console.WriteLine(minSwaps(a, n)); } } // This code is contributed by ukasp |
Javascript
<script> function minSwaps(arr, n) { // To store total number of ones let totalCount = 0; // Count total no of ones let i; for (i = 0; i < n; i++) totalCount += arr[i]; let currCount = 0; // To store count of ones in current window let maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window let j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows } // Driver Code let a = [ 1, 0, 1, 0, 1, 1 ]; let n = a.length; document.write(minSwaps(a, n)); // This code is contributed by shivanisinghss2110 </script> |
1
Complexities:
- Time Complexities: O(n)
- Space Complexities: O(1)
Contact Us