Minimum Group Flips to Make Binary Array Elements Same
Last Updated :
30 Jul, 2023
The problem statement asks us to find the minimum number of group flips required to convert a given binary array into an array that either contains all 1s or all 0s. A group flip is defined as flipping a continuous sequence of elements in the array.
For example, consider the binary array {1, 1, 0, 0, 0, 1}. We have two choices - we can either make all elements 0 or all elements 1. If we choose to make all elements 0, we need to perform two group flips (from index 2 to 4) to get {1, 1, 0, 0, 0, 0}. If we choose to make all elements 1, we need to perform one group flip (from index 0 to 1) to get {1, 1, 1, 1, 1, 1}. Since making all elements 1 takes the least group flips, we do that.
Similarly, for the input array {1, 0, 0, 0, 1, 0, 0, 1, 0, 1}, we can perform three group flips to get either {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} or {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}. Alternatively, we can perform three separate group flips from index 1 to 3, from index 5 to 6, and from index 8 to 8 to get {1, 1, 1, 0, 1, 0, 0, 1, 1, 1}.
In cases where the input array already consists of all 1s or all 0s, no group flips are needed and the output will be empty. For example, for the input array {0, 0, 0}, the output will be empty because we need not make any change. Similarly, for the input array {1, 1, 1}, the output will be empty.
In cases where the input array consists of only two distinct values, the minimum number of group flips needed will be the same, regardless of whether we choose to make all elements 0 or all elements 1. For example, for the input array {0, 1}, we can either perform one group flip from index 0 to 0 or one group flip from index 1 to 1, and the number of flips required will be the same.
Examples :
Input : arr[] = {1, 1, 0, 0, 0, 1}
Output : From 2 to 4
Explanation : 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 3
From 5 to 6
From 8 to 8
Input : arr[] = {0, 0, 0}
Output :
Explanation : Output is empty, we need not to make any change
Input : arr[] = {1, 1, 1}
Output :
Explanation : Output is empty, we need not to make any change
Input : arr[] = {0, 1}
Output :
From 0 to 0
OR
From 1 to 1
Explanation : 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.
The given problem is to convert a binary array into an array with either all 0s or all 1s, using the minimum number of group flips. A group flip means flipping a contiguous subarray of the array such that all the elements in that subarray get inverted.
The solution is based on two observations about the given problem. Firstly, there are only two types of groups in the array: groups of 0s and groups of 1s. Secondly, either the counts of both group types are the same or the difference between their counts is at most 1.
Based on these observations, we can conclude that flipping the second group and other groups of the same type as the second group will always lead to the correct answer. If the group counts are the same, it does not matter which group type we flip, as both will lead to the correct answer. If there is one extra group of 1s, we can ignore the first group and start from the second group. By doing this, we convert this case to the first case for the subarray beginning from the second group, and get the correct answer.
For example, let's consider the binary array {1, 1, 0, 1, 0, 0}. In this array, there are two groups of 0s and two groups of 1s. By flipping the second group (i.e., {0, 0}), we can make all the elements 1. Alternatively, if we flip the first group (i.e., {1, 1}), we can make all the elements 0. Hence, both flipping operations will lead to the correct answer.
Now, let's consider another example, {1, 1, 0, 0, 0, 1, 0, 0, 1, 1}. In this array, there are two groups of 0s and three groups of 1s. By ignoring the first group of 0s and starting from the second group (i.e., {0, 0}), we can convert this case to the first case for the subarray beginning from the second group. Thus, by flipping the second group and other groups of 0s, we can make all elements 1.
C++
// 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
// Java program to find the minimum
// group flips in a binary array
import 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 code
public 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
# 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 Code
if __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#
// C# program to find the minimum
// group flips in a binary array
using 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 code
public 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
JavaScript
// Define a function that takes an array and its length as input
function printGroups(arr, n) {
// Loop through the array starting from the second element
for (let i = 1; i < n; i++) {
// Check if the current element is different from the previous element
if (arr[i] !== arr[i - 1]) {
// If the current element is not the same as the first element in the array
if (arr[i] !== arr[0]) {
// Print the range of indices where the different group starts and ends
process.stdout.write(`From ${i} to `);
} else {
// If the current element is the same as the first element in the array, print the index of the last element in the previous group
console.log(i - 1);
}
}
}
// Check the last element of the array
if (arr[n - 1] !== arr[0]) {
// If the last element is different from the first element, print the index of the last element in the last group
console.log(n - 1);
}
}
// Example usage
const arr = [0, 1, 1, 0, 0, 0, 1, 1];
const n = arr.length;
printGroups(arr, n);
OutputFrom 1 to 2
From 6 to 7
Time Complexity: O(n) "The time complexity of this function is O(n), where n is the length of the input array arr. This is because the function loops through the entire array once."
Auxiliary Space: O(1) "The auxiliary space complexity of this function is O(1), because the amount of extra space used by the function does not depend on the size of the input array. The function only uses a few variables to keep track of indices and values, but the amount of memory used by these variables does not increase as the size of the input array increases."
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem