Minimum Swaps required to group all 1’s together in C++


Problem statement

Given an array of 0’s and 1’s. The task is to find the minimum number of swaps required to group all 1’s present in the array together.

Example

If input array = {1, 0, 1, 1, 0, 1} then 1 swap is required. i.e. swap first 0 with last 1.

Algorithm

  • Count total number of 1’s in the array
  • If count is x, then we need to find the subarray of length x of this array with maximum number of 1’s
  • Minimum swaps required will be the number of 0’s in the subarray of length x with maximum number of 1’s

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinSwaps(int *arr, int n) {
   int oneCnt = 0;
   for (int i = 0; i < n; ++i) {
      if (arr[i] == 1) {
         ++oneCnt;
      }
   }
   int x = oneCnt;
   int maxOnes = INT_MIN;
   int preCompute[n] = {0};
   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];
      }
   }
   for (int i = x - 1; i < n; ++i) {
      if (i == (x - 1)) {
         oneCnt = preCompute[i];
      } else {
         oneCnt = preCompute[i] - preCompute[i - x];
      } if (maxOnes < oneCnt) {
         maxOnes = oneCnt;
      }
   }
   int swapCnt = x - oneCnt;
   return swapCnt;
}
int main() {
   int arr[] = {1, 0, 1, 1, 0, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum swap count = " << getMinSwaps(arr, n) << endl;
   return 0;
}

When you compile and execute above program. It generates following output −

Output

Minimum swap count = 1

Updated on: 20-Dec-2019

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements