text: Count of integers of length N and value less than K such that they contain digits only from the given set | Javascript implementation of the approach ; Function to convert a number into vector ; Push all the digits of N from the end one by one to the vector ; If the original number was 0 ; Reverse the vector elements ; Return the required vector ; Function to return the count of B length integers which are less than C and they contain digits from set A [ ] only ; Convert number to digit array ; Case 1 : No such number possible as the generated numbers will always be greater than C ; Case 2 : All integers of length B are valid as they all are less than C ; contain 0 ; Case 3 ; Update the lower [ ] array such that lower [ i ] stores the count of elements in A [ ] which are less than i ; For first index we can 't use 0 ; Whether ( i - 1 ) digit of generated number can be equal to ( i - 1 ) digit of C ; Is digit [ i - 1 ] present in A ? ; Driver code
code: let MAX = 10 ; function numToVec ( N ) { let digit = [ ] ; while ( N != 0 ) { digit . push ( N % 10 ) ; N = Math . floor ( N / 10 ) ; } if ( digit . length == 0 ) digit . push ( 0 ) ; digit . reverse ( ) ; return digit ; } function solve ( A , B , C ) { let digit = [ ] ; let d , d2 ; digit = numToVec ( C ) ; d = A . length ; if ( B > digit . length d == 0 ) return 0 ; else if ( B < digit . length ) { if ( A [ 0 ] == 0 && B != 1 ) return Math . floor ( ( d - 1 ) * Math . pow ( d , B - 1 ) ) ; else return Math . floor ( Math . pow ( d , B ) ) ; } else { let dp = new Array ( B + 1 ) ; let lower = new Array ( MAX + 1 ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = 0 ; } for ( let i = 0 ; i < lower . length ; i ++ ) { lower [ i ] = 0 ; } for ( let i = 0 ; i < d ; i ++ ) lower [ A [ i ] + 1 ] = 1 ; for ( let i = 1 ; i <= MAX ; i ++ ) lower [ i ] = lower [ i - 1 ] + lower [ i ] ; let flag = true ; dp [ 0 ] = 0 ; for ( let i = 1 ; i <= B ; i ++ ) { d2 = lower [ digit [ i - 1 ] ] ; dp [ i ] = dp [ i - 1 ] * d ; if ( i == 1 && A [ 0 ] == 0 && B != 1 ) d2 = d2 - 1 ; if ( flag ) dp [ i ] += d2 ; flag = ( flag & ( lower [ digit [ i - 1 ] + 1 ] == lower [ digit [ i - 1 ] ] + 1 ) ) ; } return dp [ B ] ; } } let arr = [ 0 , 1 , 2 , 5 ] ; let N = 2 ; let k = 21 ; document . write ( solve ( arr , N , k ) ) ;