Generate a Binary String without any consecutive 0 ' s ▁ and ▁ at ▁ most ▁ K ▁ consecutive ▁ 1' s | C ++ Program to implement the above approach ; Function to construct the binary string ; Conditions when string construction is not possible ; Stores maximum 1 's that  can be placed in between ; Place 0 's ; Place 1 's in between ; Count remaining M 's ; Place 1 's at the end ; Place 1 's at the beginning ; Return the final string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string ConstructBinaryString ( int N , int M , int K ) { if ( M < ( N - 1 ) || M > K * ( N + 1 ) ) return " - 1" ; string ans = " " ; int l = min ( K , M / ( N - 1 ) ) ; int temp = N ; while ( temp -- ) { ans += '0' ; if ( temp == 0 ) break ; for ( int i = 0 ; i < l ; i ++ ) { ans += '1' ; } } M -= ( N - 1 ) * l ; if ( M == 0 ) return ans ; l = min ( M , K ) ; for ( int i = 0 ; i < l ; i ++ ) ans += '1' ; M -= l ; while ( M > 0 ) { ans = '1' + ans ; M -- ; } return ans ; } int main ( ) { int N = 5 , M = 9 , K = 2 ; cout << ConstructBinaryString ( N , M , K ) ; }