Count of Numbers in a Range where digit d occurs exactly K times
Given two positive integers L and R which represents a range and two more positive integers d and K. The task is to find the count of numbers in the range where digit d occurs exactly K times.
Input: L = 11, R = 100, d = 2, k = 1
Required numbers are 12, 20, 21, 23, 24, 25, 26, 27, 28, 29, 32, 42, 52, 62, 72, 82 and 92.
Input: L = 95, R = 1005, d = 0, k = 2
Prerequisites : Digit DP
Approach: Firstly, if we are able to count the required numbers upto R i.e. in the range [0, R], we can easily reach our answer in the range [L, R] by solving for from zero to R and then subtracting the answer we get after solving for from zero to L – 1. Now, we need to define the DP states.
- Since we can consider our number as a sequence of digits, one state is the position at which we are currently in. This position can have values from 0 to 18 if we are dealing with the numbers upto 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
- Second state is the count which defines the number of times, we have placed digit d so far.
- Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, maximum limit of digit we can place is digit at current position in R.
- Last state is also boolean variable nonz which helps to consider the situation if are any leading zeroes in the number we are building, we don’t need to count them.
In the final recursive call, when we are at the last position if the count of digit d is equal to K, return 1 otherwise return 0.
Below is the implementation of the above approach: