Count of Numbers in a Range divisible by m and having digit d in even positions
Given a range represented by two positive integers l and r and two integers d and m. Find the count of numbers lying in the range which is divisible by m and have digit d at even positions of the number. (i.e. digit d should not occur on odd position). Note: Both numbers l and r have same number of digits.
Input : l = 10, r = 99, d = 8, m = 2
Output : 8
Explanation :Valid numbers are 18, 28, 38, 48, 58, 68, 78 and 98.
88 is not a valid number since 8 is also present at odd position.
Input : l = 1000, r = 9999, d = 7, m = 19
Output : 6
Prerequisites: Digit DP
Approach: Firstly, if we are able to count the required numbers up to 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 up to 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 remainder which defines the modulus of the number we have made so far modulo m.
- 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, the maximum limit of digit we can place is digit at the current position in R.
If the current position is an even position, we simply place digit d and recursively solve for the next positions. But if the current position is an odd position we can place any digit except d and solve for the next positions.
Below is the implementation of the above approach.
Time Complexity: O(18 * (m – 1) * 2), if we are dealing with the numbers upto 1018
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.