Deletions of “01” or “10” in binary string to make it free from “01” or “10” in C++ Program


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.

Example

Let's see the code.

 Live Demo

#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;
}

Output

If you execute the above program, then you will get the following result.

4

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements