In this tutorial, we are going to write a program that finds the total number of pairs (01 or 10) to free the binary string from the pairs (01 and 10). Let's see an example.
Input − 101010001
Output − 4
In the above example, we have to delete a total of 4 pairs to free the binary string from the pairs (01 and 10).
The resultant string after deleting all the pairs is 0.
We have to delete all the 01 and 10 pairs from the binary string. So, the total number of pairs to be deleted is the minimum of count(1) and count(0).
Let's see the steps to solve the problem.
Initialize the binary string.
Find the zeroes and ones count.
Print the minimum from the zeroes and ones count.
Let's see the code.
#include <bits/stdc++.h> using namespace std; int findMinimumNumberOfDeletions(string str, int len) { int zeroes_count = 0, ones_count = 0; // counting zeroes and ones for (int i = 0; i < len; i++) { if (str[i] == '0') { zeroes_count++; } else { ones_count++; } } return min(zeroes_count, ones_count); } int main() { string str = "101010001"; int len = str.length(); cout << findMinimumNumberOfDeletions(str, len) << endl; return 0; }
If you execute the above program, then you will get the following result.
4
If you have any queries in the tutorial, mention them in the comment section.