Minimize flips required such that string does not any pair of consecutive 0s
Last Updated :
11 Jun, 2021
Given a binary string S, the task is to find the minimum count of flips required to modify a string such that it does not contain any pair of consecutive 0s.
Examples:
Input: S = “10001”
Output: 1
Explanation:
Flipping S[2] modifies S to “10101”.
Therefore, the required output is 1.
Input: S = “100001”
Output: 2
Explanation:
Flipping S[1] modifies S to “110001”.
Flipping S[3] modifies S to “110101”.
Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:
- Iterate over the characters of the string. For every ith character, check if S[i] and S[i + 1] are equal to ‘0’ or not. If found to be true, then increment count and update S[i + 1] to ‘1’.
- Finally, print the count obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool cntMinOperation(string S, int N)
{
int cntOp = 0;
for ( int i = 0; i < N - 1; i++) {
if (S[i] == '0' && S[i + 1] == '0' ) {
S[i + 1] = '1' ;
cntOp += 1;
}
}
return cntOp;
}
int main()
{
string S = "10001" ;
int N = S.length();
cout << cntMinOperation(S, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int cntMinOperation( char []S, int N)
{
int cntOp = 0 ;
for ( int i = 0 ; i < N - 1 ; i++)
{
if (S[i] == '0' && S[i + 1 ] == '0' )
{
S[i + 1 ] = '1' ;
cntOp += 1 ;
}
}
return cntOp;
}
public static void main(String[] args)
{
String S = "10001" ;
int N = S.length();
System.out.print(cntMinOperation(S.toCharArray(), N));
}
}
|
Python3
def cntMinOperation(S, N):
cntOp = 0
for i in range (N - 1 ):
if (S[i] = = '0' and S[i + 1 ] = = '0' ):
S[i + 1 ] = '1'
cntOp + = 1
return cntOp
if __name__ = = '__main__' :
S = "10001"
N = len (S)
print (cntMinOperation([i for i in S], N))
|
C#
using System;
class GFG
{
static int cntMinOperation( char []S, int N)
{
int cntOp = 0;
for ( int i = 0; i < N - 1; i++)
{
if (S[i] == '0' && S[i + 1] == '0' )
{
S[i + 1] = '1' ;
cntOp += 1;
}
}
return cntOp;
}
public static void Main( string [] args)
{
string S = "10001" ;
int N = S.Length;
Console.WriteLine(cntMinOperation(S.ToCharArray(), N));
}
}
|
Javascript
<script>
function cntMinOperation(S, N)
{
let cntOp = 0;
for (let i = 0; i < N - 1; i++)
{
if (S[i] == '0' && S[i + 1] == '0' )
{
S[i + 1] = '1' ;
cntOp += 1;
}
}
return cntOp;
}
let S = "10001" ;
let N = S.length;
document.write(cntMinOperation(S.split( '' ), N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...