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: 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)
Spac-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++
|
Time Complexity: O(N)
Auxiliary Space: O(1)
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
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment