Number of flips to make binary string alternate - Set 1 in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number of flips required to make the binary string alternate.

Let's say you have given a binary string "10011". To make alternate binary string, we need to flip minimum of 2 characters as "10101".

There are two possibilities for the alternate string. It will start with 0 or 1. We will check for two alternates and count the number flips required for both.

And then return the minimum of both.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
char flip(char binaryDigit) {
   return binaryDigit == '0' ? '1' : '0';
int getFlipCountToAlternateString(string binary, char expected) {
   int flipCount = 0;
   for (int i = 0; i < binary.length(); i++) {
      if (binary[i] != expected) {
      expected = flip(expected);
   return flipCount;
int main() {
   string binary = "10011";
   cout << min(getFlipCountToAlternateString(binary, '0'), getFlipCountToAlternateString(binary,       '1')) << endl;
   return 0;


If you run the above code, then you will get the following result.



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

Published on 03-Jul-2021 05:16:12