Minimum number of alternate subsequences required to be removed to empty a Binary String
Given a binary string S consisting of N characters, the task is to print the minimum number of operations required to remove all the characters from the given string S by removing a single character or removing any subsequence of alternate characters in each operation.
Input: S = “010101”
Below are the operations performed:
Operation 1: Consider the subsequence S[0, 5] i.e., “010101” as it contains alternating characters. Therefore, removing this modifies the string to “”.
Hence, the total number of operation required is 1.
Input: S = “00011”
Approach: The given problem can be solved by iterating over the string once and keep track of the maximum number of remaining 0s and 1s. Follow the steps below to solve the problem:
- Initialize a variable, say ans to store the maximum number of 0s and 1s which are still left to be removed, a variable cnt0 to count the number of 0s, and a variable cnt1 to count the number of 1s.
- Traverse the given string S from the beginning and perform the following steps:
- If the current character is 0, then increment the value of cnt0 by 1 and decrement the value of cnt1 by 1 if it is greater than 0.
- If the current character is 1, increment the value of cnt1 by 1 and decrement the value of cnt0 by 1 if it is greater than 0.
- Update the value of ans to the maximum of ans, cnt1, and cnt0.
- After completing the above steps, print the value of ans as the minimum number of operations required to remove all the characters.
Below is the implementation of the approach:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.