Minimum steps to remove substring 010 from a binary string
Last Updated :
28 Sep, 2022
Given a binary string, the task is to count the minimum steps to remove substring “010” from this binary string.
Examples:
Input: binary_string = “0101010”
Output: 2
Switching 0 to 1 at index 2 and index 4 will remove the substring 010.
Hence the number of steps needed is 2.
Input: binary_string = “010”
Output: 1
Switching any one 0 to 1 or 1 to 0 will remove the substring 010.
Hence the number of steps needed is 1.
Approach:
- Iterate the string from beginning to end-2 of the binary string.
- If in binary string continuously three characters are ‘0’, ‘1’, ‘0’ then any one character can be change so that one step will be count.
- Increase the loop counter by 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minSteps(string str)
{
int count = 0;
for ( int i = 0; i < str.length() - 2; i++) {
if (str[i] == '0' ) {
if (str[i + 1] == '1' ) {
if (str[i + 2] == '0' ) {
count++;
i += 2;
}
}
}
}
return count;
}
int main()
{
string str = "0101010" ;
cout << minSteps(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int minSteps(String str)
{
int count = 0 ;
for ( int i = 0 ; i < str.length() - 2 ; i++) {
if ((( int )str.charAt(i)) == '0' ) {
if (str.charAt(i + 1 ) == '1' ) {
if (str.charAt(i + 2 ) == '0' ) {
count++;
i += 2 ;
}
}
}
}
return count;
}
public static void main(String args[])
{
String str = "0101010" ;
System.out.println(minSteps(str));
}
}
|
Python3
def minSteps( str ):
count = 0
i = 0
while i < len ( str ) - 2 :
if str [i] = = '0' :
if ( str [i + 1 ] = = '1' ):
if ( str [i + 2 ] = = '0' ):
count = count + 1
i = i + 2
i = i + 1
return count
str = "0101010"
print (minSteps( str ))
|
C#
using System;
class GFG
{
static int minSteps( string str)
{
int count = 0;
for ( int i = 0; i < str.Length - 2; i++)
{
if ((( int )str[i]) == '0' )
{
if (str[i + 1] == '1' )
{
if (str[i + 2] == '0' )
{
count++;
i += 2;
}
}
}
}
return count;
}
public static void Main()
{
string str = "0101010" ;
Console.Write(minSteps(str));
}
}
|
PHP
<?php
function minSteps( $str )
{
$count = 0;
for ( $i = 0; $i < strlen ( $str ) - 2; $i ++)
{
if ( $str [ $i ] == '0' )
{
if ( $str [ $i + 1] == '1' )
{
if ( $str [ $i + 2] == '0' )
{
$count ++;
$i += 2;
}
}
}
}
return $count ;
}
$str = "0101010" ;
echo (minSteps( $str ));
?>
|
Javascript
<script>
function minSteps(str)
{
let count = 0;
for (let i = 0; i < str.length - 2; i++)
{
if ((str[i]) == '0' )
{
if (str[i + 1] == '1' )
{
if (str[i + 2] == '0' )
{
count++;
i += 2;
}
}
}
}
return count;
}
let str = "0101010" ;
document.write(minSteps(str));
</script>
|
Time complexity: O(n) where n is the length of binary string
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...