text: Check if all substrings of length K of a Binary String has equal count of 0 s and 1 s | C ++ program for the above approach ; Function to check if the substring of length K has equal 0 and 1 ; Traverse the string ; Check if every K - th character is the same or not ; Traverse substring of length K ; If current character is 0 ; Increment count ; Otherwise ; Decrement count ; Check for equal 0 s and 1 s ; Driver code
code: #include <iostream> NEW_LINE using namespace std ; int check ( string & s , int k ) { int n = s . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i ; j < n ; j += k ) { if ( s [ i ] != s [ j ] ) return false ; } } int c = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s [ i ] == '0' ) c ++ ; else c -- ; } if ( c == 0 ) return true ; else return false ; } int main ( ) { string s = "101010" ; int k = 2 ; if ( check ( s , k ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }