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++
#include <bits/stdc++.h>
using namespace std;
void findMinLength(string s, int n)
{
stack< int > st;
for ( int i = 0; i < n; i++) {
if (st.empty())
st.push(s[i]);
else if (s[i] == '1' )
st.pop();
else
st.push(s[i]);
}
int ans = 0;
vector< char > finalStr;
while (!st.empty()) {
ans++;
finalStr.push_back(st.top());
st.pop();
}
cout << "Length = " << ans;
if (ans != 0) {
cout << "\nString = " ;
for ( int i = 0; i < ans; i++)
cout << finalStr[i];
}
}
int main()
{
string S = "101010" ;
int N = S.size();
findMinLength(S, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findMinLength(String s, int n)
{
Stack<Character> st = new Stack<>();
for ( int i = 0 ; i < n; i++)
{
if (st.empty())
st.push(s.charAt(i));
else if (s.charAt(i) == '1' )
st.pop();
else
st.push(s.charAt(i));
}
int ans = 0 ;
Vector<Character> finalStr = new Vector<Character>();
while (st.size() > 0 )
{
ans++;
finalStr.add(st.peek());
st.pop();
}
System.out.println( "Length = " + ans);
if (ans != 0 )
{
System.out.print( "String = " );
for ( int i = 0 ; i < ans; i++)
System.out.print(finalStr.get(i));
}
}
public static void main(String args[])
{
String S = "101010" ;
int N = S.length();
findMinLength(S, N);
}
}
|
Python3
from collections import deque
def findMinLength(s, n):
st = deque()
for i in range (n):
if ( len (st) = = 0 ):
st.append(s[i])
elif (s[i] = = '1' ):
st.pop()
else :
st.append(s[i])
ans = 0
finalStr = []
while ( len (st) > 0 ):
ans + = 1
finalStr.append(st[ - 1 ]);
st.pop()
print ( "The final string size is: " , ans)
if (ans = = 0 ):
print ( "The final string is: EMPTY" )
else :
print ( "The final string is: " , * finalStr)
if __name__ = = '__main__' :
s = "0010110"
n = 7
findMinLength(s, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void findMinLength(String s, int n)
{
Stack< char > st = new Stack< char >();
for ( int i = 0; i < n; i++)
{
if (st.Count == 0)
st.Push(s[i]);
else if (s[i] == '1' )
st.Pop();
else
st.Push(s[i]);
}
int ans = 0;
List< char > finalStr = new List< char >();
while (st.Count > 0)
{
ans++;
finalStr.Add(st.Peek());
st.Pop();
}
Console.WriteLine( "Length = " + ans);
if (ans != 0)
{
Console.Write( "String = " );
for ( int i = 0; i < ans; i++)
Console.Write(finalStr[i]);
}
}
public static void Main(String []args)
{
String S = "101010" ;
int N = S.Length;
findMinLength(S, N);
}
}
|
Javascript
<script>
function findMinLength(s, n)
{
var st = [];
for ( var i = 0; i < n; i++) {
if (st.length==0)
st.push(s[i]);
else if (s[i] == '1' )
st.pop();
else
st.push(s[i]);
}
var ans = 0;
var finalStr = [];
while (st.length!=0) {
ans++;
finalStr.push(st[st.length-1]);
st.pop();
}
document.write( "Length = " + ans);
if (ans != 0) {
document.write( "<br>String = " );
for ( var i = 0; i < ans; i++)
document.write( finalStr[i]);
}
}
var S = "101010" ;
var N = S.length;
findMinLength(S, N);
</script>
|
Output:
Length = 2
String = 01
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!