K | Recursive function to find the Kth smallest binary string ; Base Case ; Return string of all 1 's  of length B ; Return string of all 0 's  of length A ; Function to find the Kth lexicographically smallest binary string with exactly A zeroes and B ones ; Stores the recurring states ; Calculate the dp values iteratively ; The last character was '0' ; The last character was '1' ; Print the binary string obtained ; Driver Code
function KthString ( A , B , K , dp ) { if ( A == 0 ) { let str = " " ; for ( let i = 0 ; i < B ; i ++ ) { str += ' ' ; } return str ; } if ( B == 0 ) { let str = " " ; for ( let i = 0 ; i < A ; i ++ ) { str += ' ' ; } return str ; } if ( K <= dp [ A - 1 ] [ B ] ) { return " " + KthString ( A - 1 , B , K , dp ) ; } else { return " " + KthString ( A , B - 1 , K - dp [ A - 1 ] [ B ] , dp ) ; } } function KthStringUtil ( A , B , K ) { let dp = new Array ( A + 1 ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( B + 1 ) . fill ( 0 ) ; } dp [ 0 ] [ 0 ] = 1 ; for ( let i = 0 ; i <= A ; ++ i ) { for ( let j = 0 ; j <= B ; ++ j ) { if ( i > 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j > 0 ) { dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } document . write ( KthString ( A , B , K , dp ) ) ; return 0 ; } let A = 3 , B = 3 , K = 7 ; KthStringUtil ( A , B , K ) ;