Skip to content
Related Articles

Related Articles

Improve Article
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:

  1. Initialize a Stack to store the minimum possible string.
  2. Traverse the given string over the range [0, N – 1].
  3. If the stack is empty, push the current binary digit S[i] in the stack.
  4. If the stack is not empty and the current bit S[i] is 1 then remove the top bit from the stack.
  5. If the current element S[i] is 0 then, push it to the stack.
  6. 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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :