Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | Function to check if a string satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current character is equal to the previous character ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Reset value of cnt ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Function to count all distinct binary strings that satisfy the given condition ; Stores the length of str ; If length of str is N ; If str satisfy the given condition ; If str does not satisfy the given condition ; Append a character '0' at end of str ; Append a character '1' at end of str ; Return total count of binary strings ; Driver Code
function checkStr ( str , P , Q ) { let N = str . length ; let prev = str [ 0 ] ; let cnt = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( str [ i ] == prev ) { cnt ++ ; } else { if ( prev == ' ' && cnt >= Q ) { return false ; } if ( prev == ' ' && cnt >= P ) { return false ; } cnt = 1 ; } prev = str [ i ] ; } if ( prev == ' ' && cnt >= Q ) { return false ; } if ( prev == ' ' && cnt >= P ) { return false ; } return true ; } function cntBinStr ( str , N , P , Q ) { let len = str . length ; if ( len == N ) { if ( checkStr ( str , P , Q ) ) return 1 ; return 0 ; } let X = cntBinStr ( str + ' ' , N , P , Q ) ; let Y = cntBinStr ( str + ' ' , N , P , Q ) ; return X + Y ; } let N = 5 , P = 2 , Q = 3 ; document . write ( cntBinStr ( " " , N , P , Q ) ) ;