Minimize removal of alternating subsequences to empty given Binary String
Last Updated :
04 May, 2021
Given a binary string S of length N, the task is to minimize the count of repetitive removal of alternating subsequence of the 0 and 1 from the given binary string S to make the string empty.
Examples:
Input: S = “0100100111”
Output: 3
Explanation:
Remove subsequence “010101” from S to modify it to “0011”.
Remove “01” from “0011” to make it “01”.
Finally, remove “01” to make it an empty string.
Input: S = “1111”
Output: 4
Approach: The given problem can be solved by observing that an alternating subsequence of 0 and 1 is to be removed and to remove all the consecutive characters 1s or 0s can only be removed at each separate operation, not in a single operation.
Therefore, the minimum number of operations required is the maximum count of consecutive 0s and 1s.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void minOpsToEmptyString(string S, int N)
{
int one = 0, zero = 0;
int x0 = 0, x1 = 0;
for ( int i = 0; i < N; i++) {
if (S[i] == '0' ) {
x0++;
x1 = 0;
}
else {
x1++;
x0 = 0;
}
zero = max(x0, zero);
one = max(x1, one);
}
cout << max(one, zero) << endl;
}
int main()
{
string S = "0100100111" ;
int N = S.length();
minOpsToEmptyString(S, N);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void
minOpsToEmptyString(String S,
int N)
{
int one = 0 , zero = 0 ;
int x0 = 0 , x1 = 0 ;
for ( int i = 0 ; i < N; i++) {
if (S.charAt(i) == '0' ) {
x0++;
x1 = 0 ;
}
else {
x1++;
x0 = 0 ;
}
zero = Math.max(x0, zero);
one = Math.max(x1, one);
}
System.out.println(
Math.max(one, zero));
}
public static void main(String[] args)
{
String S = "0100100111" ;
int N = S.length();
minOpsToEmptyString(S, N);
}
}
|
Python3
def minOpsToEmptyString(S, N):
one = 0
zero = 0
x0 = 0
x1 = 0
for i in range (N):
if (S[i] = = '0' ):
x0 + = 1
x1 = 0
else :
x1 + = 1
x0 = 0
zero = max (x0, zero)
one = max (x1, one)
print ( max (one, zero))
if __name__ = = "__main__" :
S = "0100100111"
N = len (S)
minOpsToEmptyString(S, N)
|
C#
using System;
class GFG
{
public static void
minOpsToEmptyString( string S, int N)
{
int one = 0, zero = 0;
int x0 = 0, x1 = 0;
for ( int i = 0; i < N; i++)
{
if (S[i] == '0' )
{
x0++;
x1 = 0;
}
else
{
x1++;
x0 = 0;
}
zero = Math.Max(x0, zero);
one = Math.Max(x1, one);
}
Console.WriteLine(Math.Max(one, zero));
}
static public void Main()
{
string S = "0100100111" ;
int N = S.Length;
minOpsToEmptyString(S, N);
}
}
|
Javascript
<script>
function minOpsToEmptyString(S, N)
{
let one = 0, zero = 0;
let x0 = 0, x1 = 0;
for (let i = 0; i < N; i++)
{
if (S[i] == '0' )
{
x0++;
x1 = 0;
}
else
{
x1++;
x0 = 0;
}
zero = Math.max(x0, zero);
one = Math.max(x1, one);
}
document.write(Math.max(one, zero));
}
let S = "0100100111" ;
let N = S.length;
minOpsToEmptyString(S, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...