Count of Numbers in a Range where digit d occurs exactly K times | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 20 ; int dp [ M ] [ M ] [ 2 ] [ 2 ] ; int d , K ; int count ( int pos , int cnt , int tight , int nonz , vector < int > num ) { if ( pos == num . size ( ) ) { if ( cnt == K ) return 1 ; return 0 ; } if ( dp [ pos ] [ cnt ] [ tight ] [ nonz ] != -1 ) return dp [ pos ] [ cnt ] [ tight ] [ nonz ] ; int ans = 0 ; int limit = ( tight ? 9 : num [ pos ] ) ; for ( int dig = 0 ; dig <= limit ; dig ++ ) { int currCnt = cnt ; if ( dig == d ) { if ( d != 0 || ( ! d && nonz ) ) currCnt ++ ; } int currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += count ( pos + 1 , currCnt , currTight , nonz || ( dig != 0 ) , num ) ; } return dp [ pos ] [ cnt ] [ tight ] [ nonz ] = ans ; } int solve ( int x ) { vector < int > num ; while ( x ) { num . push_back ( x % 10 ) ; x /= 10 ; } reverse ( num . begin ( ) , num . end ( ) ) ; memset ( dp , -1 , sizeof ( dp ) ) ; return count ( 0 , 0 , 0 , 0 , num ) ; } int main ( ) { int L = 11 , R = 100 ; d = 2 , K = 1 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; return 0 ; }