
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Minimum steps to remove substring 010 from a binary string in C++
Problem statement
Given a binary string, the task is to count the minimum steps to remove substring 010 from this binary string
Example
If input string is 010010 then 2 steps are required
- Convert first 0 to 1. Now string becomes 110010
- Convert last 0 to 1. Now final string becomes 110011
Algorithm
1. Iterate the string from index 0 sto n-2 2. If in binary string has consecutive three characters ‘0’, ‘1’, ‘0’ then any one character can be changed Increase the loop counter by 2
Example
#include <bits/stdc++.h> using namespace std; int getMinSteps(string str) { int cnt = 0; for (int i = 0; i < str.length() - 2; ++i) { if (str[i] == '0' && str[i + 1] == '1' && str[i+ 2] == '0') { ++cnt; i += 2; } } return cnt; } int main() { string str = "010010"; cout << "Minimum required steps = " << getMinSteps(str) << endl; return 0; }
When you compile and execute above program. It generates following output
Output
Minimum required steps = 2
- Related Articles
- Minimum Insertion Steps to Make a String Palindrome in C++
- C++ code to find minimum correct string from given binary string
- Write a Python program to remove a certain length substring from a given string
- How do I remove a substring from the end of a string in Python?
- Remove substring from StringBuilder in Java
- How to find a substring from a string in C#?
- Minimum swaps required to make a binary string alternating in C++
- Finding minimum flips in a binary string using JavaScript
- Minimum steps to delete a string after repeated deletion of palindrome substrings in C++
- Ways to remove one element from a binary string so that XOR becomes zero in C++
- Program to find minimum string size that contains given substring in Python
- How to extract a substring from inside a string in Python?
- Removing a specific substring from a string in JavaScript
- Golang Program to get a substring from the string
- Count of non-overlapping sub-strings “101” and “010” in the given binary string

Advertisements