Smallest string obtained by removing all occurrences of 01 and 11 from Binary String
Last Updated :
10 Jun, 2021
Given a binary string S , the task is to find the smallest string possible by removing all occurrences of substrings "01" and "11". After removal of any substring, concatenate the remaining parts of the string.
Examples:
Input: S = "0010110"
Output:
Length = 1 String = 0
Explanation: String can be transformed by the following steps:
0010110 ? 00110 ? 010 ? 0.
Since no occurrence of substrings 01 and 11 are remaining, the string "0" is of minimum possible length 1.
Input: S = "0011101111"
Output: Length = 0
Explanation:
String can be transformed by the following steps:
0011101111 ? 01101111 ? 011011 ? 1011 ? 11 ? "".
Approach: To solve the problem, the idea is to observe the following cases:
- 01 and 11 mean that ?1 can be removed where '?' can be 1 or 0.
- The final string will always be in the form 1000... or 000...
This problem can be solved by maintaining a Stack while processing the given string S from left to right. If the current binary digit is 0, add it to the stack, if the current binary digit is 1, remove the top bit from the stack. If the stack is empty, then push the current bit to the stack. Follow the below steps to solve the problem:
- Initialize a Stack to store the minimum possible string.
- Traverse the given string over the range [0, N - 1].
- If the stack is empty, push the current binary digit S[i] in the stack.
- If the stack is not empty and the current bit S[i] is 1 then remove the top bit from the stack.
- If the current element S[i] is 0 then, push it to the stack.
- Finally, append all the elements present in the stack from top to bottom and print it as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum
// length of the given string
void findMinLength(string s, int n)
{
// Initialize a stack
stack<int> st;
// Traverse the string
for (int i = 0; i < n; i++) {
// If the stack is empty
if (st.empty())
// Push the character
st.push(s[i]);
// If the character is 1
else if (s[i] == '1')
// Pop the top element
st.pop();
// Otherwise
else
// Push the character
// to the stack
st.push(s[i]);
}
// Initialize length
int ans = 0;
// Append the characters
// from top to bottom
vector<char> finalStr;
// Until Stack is empty
while (!st.empty()) {
ans++;
finalStr.push_back(st.top());
st.pop();
}
// Print the final string size
cout << "Length = " << ans;
// If length of the string is not 0
if (ans != 0) {
// Print the string
cout << "\nString = ";
for (int i = 0; i < ans; i++)
cout << finalStr[i];
}
}
// Driver Code
int main()
{
// Given string
string S = "101010";
// String length
int N = S.size();
// Function call
findMinLength(S, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find minimum
// length of the given string
static void findMinLength(String s, int n)
{
// Initialize a stack
Stack<Character> st = new Stack<>();
// Traverse the string
for(int i = 0; i < n; i++)
{
// If the stack is empty
if (st.empty())
// Push the character
st.push(s.charAt(i));
// If the character is 1
else if (s.charAt(i) == '1')
// Pop the top element
st.pop();
// Otherwise
else
// Push the character
// to the stack
st.push(s.charAt(i));
}
// Initialize length
int ans = 0;
// Append the characters
// from top to bottom
Vector<Character> finalStr = new Vector<Character>();
// Until Stack is empty
while (st.size() > 0)
{
ans++;
finalStr.add(st.peek());
st.pop();
}
// Print the final string size
System.out.println("Length = " + ans);
// If length of the string is not 0
if (ans != 0)
{
// Print the string
System.out.print("String = ");
for(int i = 0; i < ans; i++)
System.out.print(finalStr.get(i));
}
}
// Driver Code
public static void main(String args[])
{
// Given string
String S = "101010";
// String length
int N = S.length();
// Function call
findMinLength(S, N);
}
}
// This code is contributed by SURENDRA_GANGWAR
Python3
# Python3 program for the above approach
from collections import deque
# Function to find minimum length
# of the given string
def findMinLength(s, n):
# Initialize a stack
st = deque()
# Traverse the string from
# left to right
for i in range(n):
# If the stack is empty,
# push the character
if (len(st) == 0):
st.append(s[i])
# If the character
# is B, pop from stack
elif (s[i] == '1'):
st.pop()
# Otherwise, push the
# character to the stack
else:
st.append(s[i])
# Stores resultant string
ans = 0
finalStr = []
while (len(st) > 0):
ans += 1
finalStr.append(st[-1]);
st.pop()
# Print the final string size
print("The final string size is: ", ans)
# If length is not 0
if (ans == 0):
print("The final string is: EMPTY")
# Print the string
else:
print("The final string is: ", *finalStr)
# Driver Code
if __name__ == '__main__':
# Given string
s = "0010110"
# String length
n = 7
# Function Call
findMinLength(s, n)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find minimum
// length of the given string
static void findMinLength(String s, int n)
{
// Initialize a stack
Stack<char> st = new Stack<char>();
// Traverse the string
for(int i = 0; i < n; i++)
{
// If the stack is empty
if (st.Count == 0)
// Push the character
st.Push(s[i]);
// If the character is 1
else if (s[i] == '1')
// Pop the top element
st.Pop();
// Otherwise
else
// Push the character
// to the stack
st.Push(s[i]);
}
// Initialize length
int ans = 0;
// Append the characters
// from top to bottom
List<char> finalStr = new List<char>();
// Until Stack is empty
while (st.Count > 0)
{
ans++;
finalStr.Add(st.Peek());
st.Pop();
}
// Print the readonly string size
Console.WriteLine("Length = " + ans);
// If length of the string is not 0
if (ans != 0)
{
// Print the string
Console.Write("String = ");
for(int i = 0; i < ans; i++)
Console.Write(finalStr[i]);
}
}
// Driver Code
public static void Main(String []args)
{
// Given string
String S = "101010";
// String length
int N = S.Length;
// Function call
findMinLength(S, N);
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// JavaScript program for the above approach
// Function to find minimum
// length of the given string
function findMinLength(s, n)
{
// Initialize a stack
var st = [];
// Traverse the string
for (var i = 0; i < n; i++) {
// If the stack is empty
if (st.length==0)
// Push the character
st.push(s[i]);
// If the character is 1
else if (s[i] == '1')
// Pop the top element
st.pop();
// Otherwise
else
// Push the character
// to the stack
st.push(s[i]);
}
// Initialize length
var ans = 0;
// Append the characters
// from top to bottom
var finalStr = [];
// Until Stack is empty
while (st.length!=0) {
ans++;
finalStr.push(st[st.length-1]);
st.pop();
}
// Print the final string size
document.write( "Length = " + ans);
// If length of the string is not 0
if (ans != 0) {
// Print the string
document.write( "<br>String = ");
for(var i = 0; i < ans; i++)
document.write( finalStr[i]);
}
}
// Driver Code
// Given string
var S = "101010";
// String length
var N = S.length;
// Function call
findMinLength(S, N);
</script>
Output: Length = 2
String = 01
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2 Given a binary string S of length N, the task is to find the smallest string possible by removing all occurrences of substrings â01â and â11â. After removal of any substring, concatenate the remaining parts of the string. Examples: Input: S = "1010"Output: 2Explanation: Removal of substring "01" mod
5 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
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
Make a given Binary String non-decreasing by removing the smallest subsequence Given a binary string str of size N, the task is to find the length of the smallest subsequence such that after erasing the subsequence the resulting string will be the longest continuous non-decreasing string. Example : Input: str = "10011"Output: 1Explanation: Removal of the first occurrence of '1
8 min read
Minimum steps to remove substring 010 from a binary string 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 = "
4 min read
Most frequent character in a string after replacing all occurrences of X in a Binary String Given a string S of length N consisting of 1, 0, and X, the task is to print the character ('1' or '0') with the maximum frequency after replacing every occurrence of X as per the following conditions: If the character present adjacently to the left of X is 1, replace X with 1.If the character prese
15+ min read
Find the shortest Binary string containing one or more occurrences of given strings Given two Binary strings, S1 and S2, the task is to generate a new Binary strings (of least length possible) which can be stated as one or more occurrences of S1 as well as S2. If it is not possible to generate such a string, return -1 in output. Please note that the resultant string must not have i
6 min read
Minimum count of 0s to be removed from given Binary string to make all 1s occurs consecutively Given a binary string S of size N, the task is to find the minimum numbers of 0s that must be removed from the string S such that all the 1s occurs consecutively. Examples: Input: S = "010001011" Output: 4 Explanation: Removing the characters { S[2], S[3], S[4], S[6] } from the string S modifies the
7 min read
Replace '?' to convert given string to a binary string with maximum count of '0' and "10" Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Outp
4 min read
Minimize a binary string by repeatedly removing even length substrings of same characters Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string. Examples: Input: str ="101001"Output: "1
8 min read