Count of Numbers in a Range where digit d occurs exactly K times | JavaScript Program to find the count of numbers in a range where digit d occurs exactly K times ; states - position , count , tight , nonz ; d is required digit and K is occurrence ; This function returns the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; Nonz is true if we placed a non zero digit at the starting of the number ; At this position , number becomes smaller ; Next recursive call , also set nonz to 1 if current digit is non zero ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code to test above functions
var M = 20 ; var dp = Array . from ( Array ( M ) , ( ) => Array ( M ) ) ; var d , K ; function count ( pos , cnt , tight , nonz , num ) { if ( pos == num . length ) { if ( cnt == K ) return 1 ; return 0 ; } if ( dp [ pos ] [ cnt ] [ tight ] [ nonz ] != - 1 ) return dp [ pos ] [ cnt ] [ tight ] [ nonz ] ; var ans = 0 ; var limit = ( tight ? 9 : num [ pos ] ) ; for ( var dig = 0 ; dig <= limit ; dig ++ ) { var currCnt = cnt ; if ( dig == d ) { if ( d != 0 || ( ! d && nonz ) ) currCnt ++ ; } var currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += count ( pos + 1 , currCnt , currTight , nonz || ( dig != 0 ? 1 : 0 ) , num ) ; } return dp [ pos ] [ cnt ] [ tight ] [ nonz ] = ans ; } function solve ( x ) { var num = [ ] ; while ( x ) { num . push ( x % 10 ) ; x = parseInt ( x / 10 ) ; } num . reverse ( ) ; for ( var i = 0 ; i < M ; i ++ ) for ( var j = 0 ; j < M ; j ++ ) dp [ i ] [ j ] = Array . from ( Array ( 2 ) , ( ) => Array ( 2 ) . fill ( - 1 ) ) return count ( 0 , 0 , 0 , 0 , num ) ; } var L = 11 , R = 100 ; d = 2 , K = 1 ; document . write ( solve ( R ) - solve ( L - 1 ) ) ;