Minimum Subarray flips required to convert all elements of a Binary Array to K
Last Updated :
21 Mar, 2023
The problem statement is asking for the minimum number of operations required to convert all the elements of a given binary array arr[] to a specified value K, where K can be either 0 or 1. The operations can be performed on any index X of the array, and the operation is to flip all the elements of the subarray arr[X] ... arr[N-1].
For example, let's consider the first input given in the problem statement:
Input: N = 8, arr[ ] = {1, 0, 1, 0, 0, 1, 1, 1}, K = 0
Here, the array arr[] has N = 8 elements and the value of K is 0, which means we need to convert all the elements of arr[] to 0. We need to perform a minimum number of operations of the type described above to achieve this.
We can start by selecting an index X of the array, say X = 0, and flip all the elements from arr[0] to arr[N-1]. After this operation, the updated array becomes [0, 1, 0, 1, 1, 0, 0, 0]. We can observe that the first element of the array is 0, which is good. However, the remaining elements are not all equal to 0, so we need to perform another operation.
Next, we can choose the index X = 1 and perform the same operation of flipping all the elements from arr[1] to arr[N-1]. After this operation, the updated array becomes [0, 0, 1, 0, 0, 1, 1, 1]. We can again observe that the first two elements of the array are now 0, but the remaining elements are still not all equal to 0, so we need to perform more operations.
We can continue this process by selecting different indices and performing the flip operation until all the elements of the array become 0. In this case, we need to perform a total of 5 operations to achieve this goal.
Similarly, for the second input given in the problem statement:
Input: N = 8, arr[ ] = {1, 0, 1, 0, 0, 1, 1, 1}, K = 1
Here, the value of K is 1, which means we need to convert all the elements of arr[] to 1. We can follow the same process as described above, but we need to flip the elements of the subarray only when they are not already equal to 1. After performing a minimum number of operations, we can convert all the elements of arr[] to 1.
In this case, we need to perform a total of 4 operations to achieve this goal.
Examples:
Input: N = 8, arr[ ] = {1, 0, 1, 0, 0, 1, 1, 1}, K = 0
Output:5
Explanation:
Operation 1: X = 0 (chosen index). After modifying values the updated array arr[] is [0, 1, 0, 1, 1, 0, 0, 0].
Operation 2: X = 1 (chosen index). After modifying values the updated array arr[] is [0, 0, 1, 0, 0, 1, 1, 1].
Operation 3: X = 2 (chosen index). After modifying values the updated array arr[] is [0, 0, 0, 1, 1, 0, 0, 0].
Operation 4: X = 3 (chosen index). After modifying values the updated array arr[] is [0, 0, 0, 0, 0, 1, 1, 1].
Operation 5: X = 5 (chosen index). After modifying values the updated array arr[] is [0, 0, 0, 0, 0, 0, 0, 0].
Input: N = 8, arr[ ] = {1, 0, 1, 0, 0, 1, 1, 1}, K = 1
Output:4
Approach: The following observations is to be made:
As any index X ( < N) can be chosen and each value from index X to the index N-1 can be modified, so it can be found that the approach is to count the number of changing points in the array.
Follow the steps below to solve the above problem:
- Initialize a variable flag to inverse of K. i.e. 1 if K = 0 or vice versa, which denotes the current value.
- Initialize a variable cnt to 0, that keeps the count of the number of changing points in the array arr[].
- Traverse the array arr[] and for each index i apply the following steps:
- If the flag value and arr[i] value are different, go to the next iteration.
- If both the flag and arr[i] are equal, increase count and set flag to flag = (flag + 1) % 2.
- Print the final value of count.
Below is the implementation of the above approach:
C++14
// C++14 Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the minimum
// number of subarray flips required
int minSteps(int arr[], int n, int k)
{
int i, cnt = 0;
int flag;
if (k == 1)
flag = 0;
else
flag = 1;
// Iterate the array
for (i = 0; i < n; i++) {
// If arr[i] and flag are equal
if (arr[i] == flag) {
cnt++;
flag = (flag + 1) % 2;
}
}
// Return the answer
return cnt;
}
// Driver Code
int main()
{
int arr[] = { 1, 0, 1, 0, 0, 1, 1, 1 };
int n = sizeof(arr)
/ sizeof(arr[0]);
int k = 1;
cout << minSteps(arr, n, k);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to count the minimum
// number of subarray flips required
static int minSteps(int arr[], int n, int k)
{
int i, cnt = 0;
int flag;
if (k == 1)
flag = 0;
else
flag = 1;
// Iterate the array
for(i = 0; i < n; i++)
{
// If arr[i] and flag are equal
if (arr[i] == flag)
{
cnt++;
flag = (flag + 1) % 2;
}
}
// Return the answer
return cnt;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1, 0, 1, 0, 0, 1, 1, 1 };
int n = arr.length;
int k = 1;
System.out.print(minSteps(arr, n, k));
}
}
// This code is contributed by offbeat
Python3
# Python3 program to implement
# the above approach
# Function to count the minimum
# number of subarray flips required
def minSteps(arr, n, k):
cnt = 0
if(k == 1):
flag = 0
else:
flag = 1
# Iterate the array
for i in range(n):
# If arr[i] and flag are equal
if(arr[i] == flag):
cnt += 1
flag = (flag + 1) % 2
# Return the answer
return cnt
# Driver Code
arr = [ 1, 0, 1, 0, 0, 1, 1, 1 ]
n = len(arr)
k = 1
# Function call
print(minSteps(arr, n, k))
# This code is contributed by Shivam Singh
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to count the minimum
// number of subarray flips required
static int minSteps(int[] arr, int n, int k)
{
int i, cnt = 0;
int flag;
if (k == 1)
flag = 0;
else
flag = 1;
// Iterate the array
for(i = 0; i < n; i++)
{
// If arr[i] and flag are equal
if (arr[i] == flag)
{
cnt++;
flag = (flag + 1) % 2;
}
}
// Return the answer
return cnt;
}
// Driver code
public static void Main ()
{
int[] arr = { 1, 0, 1, 0, 0, 1, 1, 1 };
int n = arr.Length;
int k = 1;
Console.Write(minSteps(arr, n, k));
}
}
// This code is contributed by chitranayal
JavaScript
<script>
// JavaScript program for the above approach
// Function to count the minimum
// number of subarray flips required
function minSteps(arr, n, k)
{
let i, cnt = 0;
let flag;
if (k == 1)
flag = 0;
else
flag = 1;
// Iterate the array
for(i = 0; i < n; i++)
{
// If arr[i] and flag are equal
if (arr[i] == flag)
{
cnt++;
flag = (flag + 1) % 2;
}
}
// Return the answer
return cnt;
}
// Driver Code
let arr = [ 1, 0, 1, 0, 0, 1, 1, 1 ];
let n = arr.length;
let k = 1;
document.write(minSteps(arr, n, k));
</script>
Time Complexity: The function minSteps iterates through the given array once, so the time complexity is O(n), where n is the size of the array.
Auxiliary Space: The function minSteps uses a constant amount of extra space, regardless of the size of the input array. So, the auxiliary space complexity is O(1).
Space Complexity: In the given program, the input array is stored in memory, which requires O(n) space. The function minSteps uses O(1) auxiliary space. So, the total space complexity of the program is O(n) as the input array size dominates the space complexity.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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