Minimum Group Flips to Make Binary Array Elements Same - GeeksforGeeks

24 May, 2021
Given a binary array, we need to convert this array into an array that either contains all 1s or all 0s.  We need to do it using the minimum number of group flips. 
Examples : 
Input : arr[] = {1, 1, 0, 0, 0, 1}Output :  From 2 to 4Explanation : We have two choices, we make all 0s or do all 1s.  We need to do two group flips to make all elements 0 and one group flip to make all elements 1.  Since making all elements 1 takes least group flips, we do this.Input : arr[] = {1, 0, 0, 0, 1, 0, 0, 1, 0, 1}Output :  From 1 to 3From 5 to 6From 8 to 8Input : arr[] = {0, 0, 0}Output :  Explanation : Output is empty, we need not to make any changeInput : arr[] = {1, 1, 1}Output :  Explanation : Output is empty, we need not to make any changeInput : arr[] = {0, 1}Output :   From 0 to 0  ORFrom 1 to 1Explanation :  Here number of flips are same either we make all elements as 1 or all elements as 0. 
A Naive Solution is to traverse do two traversals of the array. We first traverse to find the number of groups of 0s and the number of groups of 1.  We find the minimum of these two.  Then we traverse the array and flip the 1s if groups of 1s are less. Otherwise, we flip 0s.
How to do it with one traversal of array?
An Efficient Solution is based on the below facts : 
There are only two types of groups (groups of 0s and groups of 1s)
Either the counts of both groups are same or the difference between counts is at most 1. For example, in {1, 1, 0, 1, 0, 0} there are two groups of 0s and two groups of 1s.  In example, {1, 1, 0, 0, 0, 1, 0, 0, 1, 1}, count of groups of 1 is one more than the counts of 0s.
Based on the above facts, we can conclude that if we always flip the second group and other groups that of the same type as the second group, we always get the correct answer.  In the first case, when group counts are the same, it does not matter which group type we flip as both will lead to the correct answer.  In the second case, when there is one extra, by ignoring the first group and starting from the second group, we convert this case to first case (for subarray beginning from the second group) and get the correct answer.
C++
Java
Python3
C#
Javascript
// C++ program to find the minimum// group flips in a binary array#include <iostream>using namespace std; void printGroups(bool arr[], int n) {     // Traverse through all array elements  // starting from the second element  for (int i = 1; i < n; i++) {         // If current element is not same    // as previous    if (arr[i] != arr[i - 1]) {             // If it is same as first element      // then it is starting of the interval      // to be flipped.      if (arr[i] != arr[0])        cout << "From " << i << " to ";       // If it is not same as previous      // and same as first element, then      // previous element is end of interval      else        cout << (i - 1) << endl;    }  }   // Explicitly handling the end of  // last interval  if (arr[n - 1] != arr[0])    cout << (n - 1) << endl;} int main() {  bool arr[] = {0, 1, 1, 0, 0, 0, 1, 1};  int n = sizeof(arr) / sizeof(arr[0]);  printGroups(arr, n);  return 0;}
// Java program to find the minimum// group flips in a binary arrayimport java.io.*;import java.util.*; class GFG {     static void printGroups(int arr[], int n){         // Traverse through all array elements    // starting from the second element    for(int i = 1; i < n; i++)    {                // If current element is not same       // as previous       if (arr[i] != arr[i - 1])       {                       // If it is same as first element           // then it is starting of the interval           // to be flipped.           if (arr[i] != arr[0])               System.out.print("From " + i + " to ");                       // If it is not same as previous           // and same as first element, then           // previous element is end of interval           else               System.out.println(i - 1);       }    }         // Explicitly handling the end of    // last interval    if (arr[n - 1] != arr[0])        System.out.println(n - 1);}     // Driver codepublic static void main(String[] args){    int arr[] = {0, 1, 1, 0, 0, 0, 1, 1};    int n = arr.length;         printGroups(arr, n);}} // This code is contributed by coder001
# Python3 program to find the minimum# group flips in a binary array def printGroups(arr, n):         # Traverse through all array elements    # starting from the second element    for i in range(1, n):                 # If current element is not same        # as previous        if (arr[i] != arr[i - 1]):                         # If it is same as first element            # then it is starting of the interval            # to be flipped.            if (arr[i] != arr[0]):                print("From", i, "to ", end = "")             # If it is not same as previous            # and same as the first element, then            # previous element is end of interval            else:                print(i - 1)     # Explicitly handling the end of    # last interval    if (arr[n - 1] != arr[0]):        print(n - 1) # Driver Codeif __name__ == '__main__':         arr = [ 0, 1, 1, 0, 0, 0, 1, 1 ]    n = len(arr)         printGroups(arr, n)     # This code is contributed by Bhupendra_Singh
// C# program to find the minimum// group flips in a binary arrayusing System; class GFG{     static void printGroups(int []arr, int n){         // Traverse through all array elements    // starting from the second element    for(int i = 1; i < n; i++)    {        // If current element is not same       // as previous       if (arr[i] != arr[i - 1])       {                       // If it is same as first element           // then it is starting of the interval           // to be flipped.           if (arr[i] != arr[0])               Console.Write("From " + i + " to ");                       // If it is not same as previous           // and same as first element, then           // previous element is end of interval           else               Console.WriteLine(i - 1);       }    }         // Explicitly handling the end    // of last interval    if (arr[n - 1] != arr[0])        Console.WriteLine(n - 1);}     // Driver codepublic static void Main(String[] args){    int []arr = { 0, 1, 1, 0, 0, 0, 1, 1 };    int n = arr.Length;         printGroups(arr, n);}} // This code is contributed by amal kumar choubey
<script> // JavaScript program to find the minimum// group flips in a binary array function printGroups(arr, n) {     // Traverse through all array elements  // starting from the second element  for (var i = 1; i < n; i++) {         // If current element is not same    // as previous    if (arr[i] != arr[i - 1]) {             // If it is same as first element      // then it is starting of the interval      // to be flipped.      if (arr[i] != arr[0])        document.write( "From " + i + " to ");       // If it is not same as previous      // and same as first element, then      // previous element is end of interval      else        document.write(i - 1 + "<br>");    }  }   // Explicitly handling the end of  // last interval  if (arr[n - 1] != arr[0])    document.write(n - 1 + "<br>");} var arr = [0, 1, 1, 0, 0, 0, 1, 1];var n = arr.length;printGroups(arr, n); </script>
From 1 to 2
From 6 to 7
Time Complexity:  O(n)Auxiliary Space:  O(1)
bgangwar59
coder001
Amal Kumar Choubey
itsok
array-traversal-question
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array of size n and a number k, find all elements that appear more than n/k times
Maximum and minimum of an array using minimum number of comparisons