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 stringvoid 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 Codeint 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 approachimport java.util.*;class GFG{// Function to find minimum// length of the given stringstatic 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 Codepublic 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 approachfrom collections import deque# Function to find minimum length# of the given stringdef 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 Codeif __name__ == '__main__': # Given string s = "0010110" # String length n = 7 # Function Call findMinLength(s, n) |
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.
Recommended Posts:
- Remove all continuous occurrences of 'a' and all occurrences of 'b'
- Minimize ASCII values sum after removing all occurrences of one character
- Swap all occurrences of two characters to get lexicographically smallest string
- String obtained by reversing and complementing a Binary string K times
- Lexicographically smallest string obtained after concatenating array
- Print string after removing all (“10” or “01”) from the binary string
- Find i'th Index character in a binary string obtained after n iterations
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest subsequence possible by removing a character from given string
- Find the number obtained after concatenation of binary representation of M and N
- Rearrange a binary string as alternate x and y occurrences
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
- Check if a string can be obtained by rotating another string 2 places
- Check if a string can be obtained by rotating another string d places
- Check if a string can be obtained by appending subsequences of another string
- Check if a binary string has two consecutive occurrences of one everywhere
- Replace all occurrences of string AB with C without using extra space
- Remove all occurrences of a character in a string
- Number of permutations of a string in which all the occurrences of a given character occurs together
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SURENDRA_GANGWAR

