Check if a binary string contains consecutive same or not in C++

Suppose we have a binary string. Our task is to check whether the string has consecutive same characters or not. If there are consecutive same characters, then that is invalid, otherwise valid. Then the string “101010” is valid, but “10111010” is invalid.

To solve this problem, we will traverse from left to right, if two consecutive characters are the same, then return false, otherwise true.


 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
bool isConsecutiveSame(string str){
   int len = str.length();
   for(int i = 0; i<len - 1; i++){
      if(str[i] == str[i + 1])
      return false;
   return true;
int main() {
   string str = "101010";
      cout << "No consecutive same characters";
      cout << "Consecutive same characters found";


No consecutive same characters

Updated on: 21-Oct-2019


Kickstart Your Career

Get certified by completing the course

Get Started