Minimize flips on K-length subarrays required to make all array elements equal to 1
Last Updated :
11 Jul, 2022
Given a binary array arr[] of size N and a positive integer K, the task is to find the minimum number of times any subarray of size K from the given array arr[] is required to be flipped to make all array elements equal to 1. If it is not possible to do so, then print “-1”.
Examples:
Input: arr[] = {0, 1, 0}, K = 1
Output: 2
Explanation:
Perform the operation in the following order:
Operation 1: Flip all elements present in the subarray {arr[0]}. Now, the array modifies to {1, 1, 0}.
Operation 2: Flip all elements present in the subarray {arr[2]}. Now the array modifies to {1, 1, 1}.
Therefore, the total number of operations required is 2.
Input: arr[] = {1, 1, 0}, K = 2
Output: -1
Approach: Follow the steps below to solve the problem:
- Initialize an auxiliary array, say isFlipped[] of size N.
- Initialize a variable, say ans, to store the minimum number of K-length subarray flips required.
- Traverse the given array arr[] using a variable i and perform the following steps:
- If the value of i is greater than 0, then update the value of isFlipped[i] as (isFlipped[i] + isFlipped[i – 1])%2.
- Check if the current element needs to be flipped, i.e. if the value of A[i] is 0 and isFlipped[i] is not set OR, the value of A[i] is 1 and isFlipped[i] is set, then perform the following steps:
- If such a K-length subarray is not possible, then print “-1” and break out of the loop, as it is impossible to make all array elements equal to 1.
- Increment ans and isFlipped[i] by 1, and decrement isFlipped[i + K] by 1.
- Otherwise, continue to the next iteration.
- After completing the above steps, if all array elements can be made 1, then print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minimumOperations(vector< int >& A, int K)
{
vector< int > isflipped(A.size(), 0);
int ans = 0;
for ( int i = 0; i < A.size(); i++) {
if (i > 0) {
isflipped[i] += isflipped[i - 1];
isflipped[i] %= 2;
}
if (A[i] == 0 && !isflipped[i]) {
if ((A.size() - i + 1) <= K) {
cout << -1;
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
}
else if (A[i] == 1 && isflipped[i]) {
if ((A.size() - i + 1) <= K) {
cout << -1;
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
}
}
cout << ans;
}
int main()
{
vector< int > arr = { 0, 1, 0 };
int K = 1;
minimumOperations(arr, K);
return 0;
}
|
Java
class GFG
{
static void minimumOperations( int [] A, int K)
{
int [] isflipped = new int [A.length+ 1 ];
int ans = 0 ;
for ( int i = 0 ; i < A.length; i++)
{
if (i > 0 ) {
isflipped[i] += isflipped[i - 1 ];
isflipped[i] %= 2 ;
}
if (A[i] == 0 && isflipped[i] == 0 )
{
if ((A.length - i + 1 ) <= K)
{
System.out.println(- 1 );
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
} else if (A[i] == 1 && isflipped[i] != 0 )
{
if ((A.length - i + 1 ) <= K)
{
System.out.println(- 1 );
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
int [] arr = { 0 , 1 , 0 };
int K = 1 ;
minimumOperations(arr, K);
}
}
|
Python3
def minimumOperations(A, K):
isflipped = [ 0 ] * ( len (A) + 1 )
ans = 0
for i in range ( len (A)):
if (i > 0 ):
isflipped[i] + = isflipped[i - 1 ]
isflipped[i] % = 2
if (A[i] = = 0 and not isflipped[i]):
if (( len (A) - i + 1 ) < = K):
print ( - 1 )
return
ans + = 1
isflipped[i] + = 1
isflipped[i + K] - = 1
elif (A[i] = = 1 and isflipped[i]):
if (( len (A) - i + 1 ) < = K):
print ( - 1 )
return
ans + = 1
isflipped[i] + = 1
isflipped[i + K] - = 1
print (ans)
if __name__ = = "__main__" :
arr = [ 0 , 1 , 0 ]
K = 1
minimumOperations(arr, K)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void minimumOperations(List< int > A, int K)
{
List< int > isflipped = new List< int >();
for ( int i = 0; i < A.Count + 1; i++)
isflipped.Add(0);
int ans = 0;
for ( int i = 0; i < A.Count; i++)
{
if (i > 0)
{
isflipped[i] += isflipped[i - 1];
isflipped[i] %= 2;
}
if (A[i] == 0 && isflipped[i] == 0)
{
if ((A.Count - i + 1) <= K)
{
Console.Write(-1);
return ;
}
ans += 1;
isflipped[i] += 1;
isflipped[i + K] -= 1;
}
else if (A[i] == 1 && isflipped[i] != 0)
{
if ((A.Count - i + 1) <= K)
{
Console.Write(-1);
return ;
}
ans += 1;
isflipped[i] += 1;
isflipped[i + K] -= 1;
}
}
Console.WriteLine(ans);
}
public static void Main()
{
List< int > arr = new List< int >(){ 0, 1, 0 };
int K = 1;
minimumOperations(arr, K);
}
}
|
Javascript
<script>
function minimumOperations(A, K)
{
let isflipped = [];
for (let i = 0; i < A.length + 1; i++)
{
isflipped[i] =0;
}
let ans = 0;
for (let i = 0; i < A.length; i++)
{
if (i > 0) {
isflipped[i] += isflipped[i - 1];
isflipped[i] %= 2;
}
if (A[i] == 0 && isflipped[i] == 0)
{
if ((A.length - i + 1) <= K)
{
document.write(-1);
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
} else if (A[i] == 1 && isflipped[i] != 0)
{
if ((A.length - i + 1) <= K)
{
document.write(-1);
return ;
}
ans++;
isflipped[i]++;
isflipped[i + K]--;
}
}
document.write(ans);
}
let arr = [ 0, 1, 0 ];
let K = 1;
minimumOperations(arr, K);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2:- Sliding Window
C++
#include <bits/stdc++.h>
using namespace std;
int minKBitFlips( int A[], int K, int N)
{
queue< int > flip;
int count = 0;
for ( int i = 0; i < N; i++)
{
if (flip.size() > 0 && (i - flip.front() >= K)) {
flip.pop();
}
if (A[i] % 2 == flip.size() % 2) {
if (i + K - 1 >= N) {
return -1;
}
flip.push(i);
count++;
}
}
return count;
}
int main()
{
int A[] = { 0, 1, 0 };
int N = sizeof (A) / sizeof (A[0]);
int K = 1;
int ans = minKBitFlips(A, K, 3);
cout << ans;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int minKBitFlips( int [] A, int K)
{
Queue<Integer> flip = new LinkedList<>();
int count = 0 ;
for ( int i = 0 ; i < A.length; i++) {
if (!flip.isEmpty() && (i - flip.peek() >= K)) {
flip.poll();
}
if (A[i] % 2 == flip.size() % 2 ) {
if (i + K - 1 >= A.length) {
return - 1 ;
}
flip.offer(i);
count++;
}
}
return count;
}
public static void main(String[] args)
{
int [] A = { 0 , 1 , 0 };
int K = 1 ;
int ans = minKBitFlips(A, K);
System.out.println(ans);
}
}
|
Python3
def minKBitFlips(A, K, N):
flip = []
count = 0
for i in range (N):
if ( len (flip) > 0 and (i - flip[ 0 ] > = K)):
flip.pop( 0 )
if (A[i] % 2 = = len (flip) % 2 ):
if (i + K - 1 > = N):
return - 1
flip.append(i)
count + = 1
return count
A = [ 0 , 1 , 0 ]
N = len (A)
K = 1
ans = minKBitFlips(A, K, 3 )
print (ans)
|
C#
using System;
using System.Collections;
class GFG {
static int minKBitFlips( int [] A, int K)
{
Queue flip = new Queue();
int count = 0;
for ( int i = 0; i < A.Length; i++)
{
if (flip.Count > 0 && (i - ( int )flip.Peek() >= K)) {
flip.Dequeue();
}
if (A[i] % 2 == flip.Count % 2) {
if (i + K - 1 >= A.Length) {
return -1;
}
flip.Enqueue(i);
count++;
}
}
return count;
}
static void Main() {
int [] A = { 0, 1, 0 };
int K = 1;
int ans = minKBitFlips(A, K);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
function minKBitFlips(A,K)
{
let flip = [];
let count = 0;
for (let i = 0; i < A.length; i++) {
if (flip.length!=0 && (i - flip[0] >= K)) {
flip.shift();
}
if (A[i] % 2 == flip.length % 2) {
if (i + K - 1 >= A.length) {
return -1;
}
flip.push(i);
count++;
}
}
return count;
}
let A=[0, 1, 0 ];
let K = 1;
let ans = minKBitFlips(A, K);
document.write(ans);
</script>
|
Complexity Analysis:-
Time Complexity: O(N), where N is the length of the array.
Space Complexity: O(N).
Approach 3:- Greedy
C++
#include <bits/stdc++.h>
using namespace std;
int minKBitFlips( int A[], int K, int N)
{
int temp[N];
memset (temp, 0, N);
int count = 0;
int flip = 0;
count++;
for ( int i = 0; i < N; ++i) {
flip ^= temp[i];
if (A[i] == flip) {
count++;
if (i + K > N) {
return -1;
}
flip ^= 1;
if (i + K < N) {
temp[i + K] ^= 1;
}
}
}
return count;
}
int main()
{
int A[] = { 0, 1, 0 };
int N = sizeof (A) / sizeof (A[0]);
int K = 1;
int ans = minKBitFlips(A, K, N);
cout << ans;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int minKBitFlips( int [] A, int K)
{
int [] temp = new int [A.length];
int count = 0 ;
int flip = 0 ;
for ( int i = 0 ; i < A.length; ++i) {
flip ^= temp[i];
if (A[i] == flip) {
count++;
if (i + K > A.length) {
return - 1 ;
}
flip ^= 1 ;
if (i + K < A.length) {
temp[i + K] ^= 1 ;
}
}
}
return count;
}
public static void main(String[] args)
{
int [] A = { 0 , 1 , 0 };
int K = 1 ;
int ans = minKBitFlips(A, K);
System.out.println(ans);
}
}
|
Python3
def minKBitFlips(A, K):
temp = [ 0 ] * len (A)
count = 0
flip = 0
for i in range ( len (A)):
flip ^ = temp[i]
if (A[i] = = flip):
count + = 1
if (i + K > len (A)) :
return - 1
flip ^ = 1
if (i + K < len (A)):
temp[i + K] ^ = 1
return count
A = [ 0 , 1 , 0 ]
K = 1
ans = minKBitFlips(A, K)
print (ans)
|
Javascript
<script>
function minKBitFlips(A, K)
{
let temp = new Array(A.length);
let count = 0;
let flip = 0;
for (let i = 0; i < A.length; ++i) {
flip ^= temp[i];
if (A[i] == flip) {
count++;
if (i + K > A.length) {
return -1;
}
flip ^= 1;
if (i + K < A.length) {
temp[i + K] ^= 1;
}
}
}
return count;
}
let A = [ 0, 1, 0 ];
let K = 1;
let ans = minKBitFlips(A, K);
document.write(ans);
</script>
|
C#
using System;
class GFG {
static int minKBitFlips( int [] A, int K)
{
int [] temp = new int [A.Length];
int count = 0;
int flip = 0;
for ( int i = 0; i < A.Length; ++i) {
flip ^= temp[i];
if (A[i] == flip) {
count++;
if (i + K > A.Length) {
return -1;
}
flip ^= 1;
if (i + K < A.Length) {
temp[i + K] ^= 1;
}
}
}
return count;
}
public static void Main(String[] args)
{
int [] A = { 0, 1, 0 };
int K = 1;
int ans = minKBitFlips(A, K);
Console.Write(ans);
}
}
|
Complexity Analysis:-
Time Complexity: O(N), where N is the length of the array.
Space Complexity: O(N).
Related Topic: Subarrays, Subsequences, and Subsets in Array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...