Blog Archive

Split the binary string into substrings with equal number of 0s and 1s

 Split the binary string into substrings with equal number of 0s and 1s

Q.Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1

Example:

Input: str = “0100110101”
Output: 4
The required substrings are “01”, “0011”, “01” and “01”.

Input: str = “0111100010”
Output: 3


SOLUTION

#include <iostream >
    using namespace std;
int countBinary(string sint n){
    int count0 = 0;
    int count1 = 0;
    int count = 0;
    for (int i = 0i < ni++) {
        if (s[i] == '0') {
            count0++;
        }
        else {
            count1++;
        }
        if (count0 == count1) {
            count++;
        }
    }
    if (count0 != count1) {
        return -1;
    }

    return count;
}
int main() {
    string s;
    cin >> s;
    int n = s.length();
    int num = countBinary(sn);
    cout << num;
    return 0;
}

Data Structures and Algorithms


Thank You 

1 comment:

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...