text: Check if it is possible to rearrange a binary string with alternate 0 s and 1 s | CPP program to check if we can rearrange a string such that it has alternate 0 s and 1 s . ; function to check the binary string ; length of string ; count zero 's ; count one 's ; if length is even ; if length is odd ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_possible ( string s ) { int l = s . length ( ) ; int one = 0 , zero = 0 ; for ( int i = 0 ; i < l ; i ++ ) { if ( s [ i ] == '0' ) zero ++ ; else one ++ ; } if ( l % 2 == 0 ) return ( one == zero ) ; else return ( abs ( one - zero ) == 1 ) ; } int main ( ) { string s = "100110" ; if ( is_possible ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }