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.
Examples:
Input: S = “010101”
Output: 1
Explanation:
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”
Output: 3
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:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of operations to empty a binary stringint minOpsToEmptyString(string s){ // Stores the resultant number of // operations int ans = INT_MIN; // Stores the number of 0s int cn0 = 0; // Stores the number of 1s int cn1 = 0; // Traverse the given string for (int i = 0; i < s.length(); i++) { if (s[i] == '0') { // To balance 0 with 1 // if possible if (cn1 > 0) cn1--; // Increment the value // of cn0 by 1 cn0++; } else { // To balance 1 with 0 // if possible if (cn0 > 0) cn0--; // Increment the value // of cn1 cn1++; } // Update the maximum number // of unused 0s and 1s ans = max({ ans, cn0, cn1 }); } // Print the resultant count cout << ans;} // Driver Codeint main(){ string S = "010101"; minOpsToEmptyString(S); return 0;} |
1
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.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live


