Given a binary string str of size N, the task is to find the length of the smallest subsequence such that after erasing the subsequence the resulting string will be the longest continuous non-decreasing string.
Input: str = “10011”
Explanation: Removal of the first occurrence of ‘1’ results in a non-decreasing subsequence, i.e “0011”.
Input: str = “11110000”
Approach: The problem can be solved based on the following observations:
The non-decreasing subsequences can be of the following 3 types:
- Case 1 : 00000…..
- Case 2 : 11111…..
- Case 3 : 0000….111111….
Follow the given steps to solve the problem:
- Iterate over the characters of the string.
- Count the number of 0s and 1s present in the string
- To generate non-decreasing subsequences of the form “0000….”, minimum removals required is the count of 1s in the string
- To generate non-decreasing subsequences of the form “1111….”, minimum removals required is the count of 0s in the string
- To generate non-decreasing subsequences of the form “0000…1111….”, minimum removals required can be obtained using the following steps:
- Iterate over the characters of the string. Consider removing the 1s from the left and removing the 0s from the right end of the string.
- Update the minimum after each iteration.
- Finally, print the minimum removals obtained in the above three cases as the required answer.
Below is the implementation of the above approach :
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.