Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimum splits in a binary string such that every substring is a power of 4 or 6.
Next article icon

Minimum steps to remove substring 010 from a binary string

Last Updated : 28 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  1. Iterate the string from beginning to end-2 of the binary string.
  2. 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.
  3. Increase the loop counter by 2.

Below is the implementation of the above approach: 

C++




// CPP program to calculate steps
// to remove substring 010
// from a binary string
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum steps
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') {
 
                    // substring "010" found
                    count++;
                    i += 2;
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
 
    // Get the binary string
    string str = "0101010";
 
    // Find the minimum steps
    cout << minSteps(str);
 
    return 0;
}
 
 

Java




// Java program to calculate steps
// to remove substring 010
// from a binary string
import java.util.*;
 
class GFG{
 
// Function to find the minimum steps
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') {
 
                    // substring "010" found
                    count++;
                    i += 2;
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
public static void main(String args[])
{
 
    // Get the binary string
    String str = "0101010";
 
    // Find the minimum steps
    System.out.println(minSteps(str));
}
}
 
 

Python3




# Python3 program to calculate steps
# to remove substring 010
# from a binary string
 
# Function to find the minimum steps
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'):
                     
                    # substring "010" found
                    count = count + 1
                    i = i + 2
        i = i + 1
     
    return count
 
# Driver code
 
# Get the binary string
str = "0101010"
 
# Find the minimum steps
print(minSteps(str))
         
# This code is contributed
# by Shashank_Sharma
 
 

C#




// C# program to calculate steps
// to remove substring 010
// from a binary string
using System;
 
class GFG
{
 
// Function to find the minimum steps
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')
                {
 
                    // substring "010" found
                    count++;
                    i += 2;
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
public static void Main()
{
 
    // Get the binary string
    string str = "0101010";
 
    // Find the minimum steps
    Console.Write(minSteps(str));
}
}
 
// This code is contributed by ChitraNayal
 
 

PHP




<?php
// PHP program to calculate steps to remove
// substring 010 from a binary string
 
// Function to find the minimum steps
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')
                {
 
                    // substring "010" found
                    $count++;
                    $i += 2;
                }
            }
        }
    }
 
    return $count;
}
 
// Driver code
 
// Get the binary string
$str = "0101010";
 
// Find the minimum steps
echo(minSteps($str));
 
// This code is contributed
// by Shivi_Aggarwal
?>
 
 

Javascript




<script>
 
// js program to calculate steps
// to remove substring 010
// from a binary string
 
// Function to find the minimum steps
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')
                {
 
                    // substring "010" found
                    count++;
                    i += 2;
                }
            }
        }
    }
 
    return count;
}
 
// Driver code
 
// Get the binary string
let str = "0101010";
 
// Find the minimum steps
document.write(minSteps(str));
 
// This code is contributed by mohit kumar 29.
 
</script>
 
 
Output
2

Time complexity: O(n) where n is the length of binary string

Auxiliary Space: O(1)



Next Article
Minimum splits in a binary string such that every substring is a power of 4 or 6.

S

SURENDRA_GANGWAR
Improve
Article Tags :
  • DSA
  • Strings
  • binary-string
  • substring
Practice Tags :
  • Strings

Similar Reads

  • Print string after removing all (“10” or “01”) from the binary string
    Given a binary string str consisting of only 0's and 1's, the task is to print the string after removing the occurrences of "10" and "01" from the string one by one. Print -1 if the string becomes null. Examples: Input: str = "101100" Output: -1 Explanation: In the first step, "10" at index 0 and 1
    9 min read
  • Minimum number of steps needed to remove the substring K from given string
    Given a binary string S, and a substring K, the task is to find the minimum no of steps required to flip the characters in a binary string such that it doesn't contain the given substring K. Note: In one step we can change 0 to 1 or vice versa.Examples: Input: S = "0111011", K = "011" Output: 2 Expl
    5 min read
  • Minimum substring reversals required to make given Binary String alternating
    Given a binary string S of length N, the task is to count the minimum number substrings of S that is required to be reversed to make the string S alternating. If it is not possible to make string alternating, then print "-1". Examples: Input: S = "10001110"Output: 2Explanation:In the first operation
    7 min read
  • Minimum splits in a binary string such that every substring is a power of 4 or 6.
    Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: Input: 100110110 Output: 3 The string can be split into a minimum of three substrings
    11 min read
  • Minimum substring flips required to convert a Binary String to another
    Given two binary strings S1 and S2 of size N and M respectively, the task is to find the minimum number of reversal of substrings of equal characters required to convert the string S1 to S2. If it is not possible to convert the string S1 to S2, then print "-1". Examples: Input: S1 = "100001", S2 = "
    6 min read
  • Minimize removal of substring of 0s to remove all occurrences of 0s from a circular Binary String
    Given circular binary string S of size N, the task is to count the minimum number of consecutive 0s required to be removed such that the string contains only 1s. A circular string is a string whose first and last characters are considered to be adjacent to each other. Examples: Input: S = "11010001"
    6 min read
  • Maximum count of “010..” subsequences that can be removed from given Binary String
    Given a binary string S consisting of size N, the task is to find the maximum number of binary subsequences of the form "010.." of length at least 2 that can be removed from the given string S. Examples: Input: S = "110011010"Output: 3Explanation:Following are the subsequence removed:Operation 1: Ch
    6 min read
  • Count ways to generate Binary String not containing "0100" Substring
    Given the number N, count the number of ways to create a binary string (the string that contains characters as zero or one) of size N such that it does not contain "0100" as a substring. A substring is a contiguous sequence of characters within a string. Examples: Input: N = 4Output: 15Explanation:
    15+ min read
  • Minimize deletions in a Binary String to remove all subsequences of the form "0101"
    Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string. Examples: Input: S = "0101101"Output: 2Explanation: Removing S[1] and S[5] modifies the string to 00111.
    6 min read
  • Minimum shifts of substrings of 1s required to group all 1s together in a given Binary string
    Given a binary string S of length N, the task is to print the minimum number of indices, substrings consisting only of 1s are required to be shifted such that all 1s present in the string are grouped together. Examples: Input: S = "00110111011"Output: 2Explanation: Operation 1: Shift substring {S[2]
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences