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: 2
Explanation: Removal of substring “01” modifies string S to “10”.
Input: S = “111”
Output: 1
Stack-based Approach: Refer to the previous article to find the length of the smallest string possible by given operations.
Time Complexity: O(N)
Auxiliary Space: O(N)
Space-Optimized Approach: The above approach can be space-optimized by only storing the length of the characters not removed. Follow the steps below to solve the problem:
- Initialize a variable, say st as 0, to store the length of the smallest string possible.
- Iterate over the characters of the string S and perform the following steps:
- If st is greater than 0 and S[i] is equal to ‘1‘, then pop the last element by decrementing st by 1.
- Otherwise, increment st by 1.
- Finally, after completing the above steps, print the answer obtained in st.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int shortestString(string S, int N)
{
int st = 0;
for ( int i = 0; i < N; i++) {
if (st && S[i] == '1' ) {
st--;
}
else {
st++;
}
}
return st;
}
int main()
{
string S = "1010" ;
int N = S.length();
cout << shortestString(S, N);
return 0;
}
|
Java
public class GFG_JAVA {
static int shortestString(String S, int N)
{
int st = 0 ;
for ( int i = 0 ; i < N; i++) {
if (st > 0 && S.charAt(i) == '1' ) {
st--;
}
else {
st++;
}
}
return st;
}
public static void main(String[] args)
{
String S = "1010" ;
int N = S.length();
System.out.println(shortestString(S, N));
}
}
|
Python3
def shortestString(S, N) :
st = 0 ;
for i in range (N) :
if (st and S[i] = = '1' ) :
st - = 1 ;
else :
st + = 1 ;
return st;
if __name__ = = "__main__" :
S = "1010" ;
N = len (S);
print (shortestString(S, N));
|
C#
using System;
public class GFG_JAVA {
static int shortestString( string S, int N)
{
int st = 0;
for ( int i = 0; i < N; i++) {
if (st > 0 && S[i] == '1' ) {
st--;
}
else {
st++;
}
}
return st;
}
public static void Main( string [] args)
{
string S = "1010" ;
int N = S.Length;
Console.WriteLine(shortestString(S, N));
}
}
|
Javascript
<script>
function shortestString(S, N)
{
let st = 0;
for (let i = 0; i < N; i++) {
if (st > 0 && S[i] == '1' ) {
st--;
}
else {
st++;
}
}
return st;
}
let S = "1010" ;
let N = S.length;
document.write(shortestString(S, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
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!
Last Updated :
14 Sep, 2021
Like Article
Save Article