Minimum number of characters to be removed to make a binary string alternate

Given a binary string, write a function that will find minimum number of characters that can be removed from it so that it becomes alternate. A binary string is said to be alternate if there are no consecutive 0's or 1's


s = "0011"

We need to remove two zeros and two 1 ones to make it alternate


1. Traverse the string

    a. If the currennt character is different from next character, then dont delete
    b. else, we need to delete one character

C++ Program

using namespace std;
//finds the min chars to be removed
int minCharsRemoved(string s)
    int count = 0;
    int n = s.length()-1;
    for (int i=0; i<n; i++)
        //If curr and next are same
        if (s[i] == s[i+1])
    return count;

int main()
    string s = "0011";
    cout << minCharsRemoved(s) << endl;
    return 0;
Try It


Next > < Prev
Scroll to Top