Blog Archive

Minimum Changes To Make Alternating Binary String


You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.

The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.

Return the minimum number of operations needed to make s alternating

Example :

Input: s = "0100"
Output: 1

Explanation: If you change the last character to '1', s will be "0101", which is alternating 

SOLUTION

int minOperations(string s)
{
    int n = s.length();

    if (n <= 1)
        return 0;

    int c1 = 0;
    int c0 = 0;
    for (int i = 0i < ni++)
    {
        if (i % 2)
        {
            if (s[i] == '1')
                c0++;
            else
                c1++;
        }
        else
        {
            if (s[i] == '0')
                c0++;
            else
                c1++;
        }
    }

    return min(c0c1);
}
Data structures and algorithm - String Data Structure


Thank You...

No comments:

Post a 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...