Count of numbers from range [L, R] whose sum of digits is Y | Set 2
Given three positive integers L, R and Y, the task is to count the numbers in the range [L, R] whose sum of digits is equal to Y
Input: L = 500, R = 1000, Y = 6
Numbers in the range [500, 600] whose sum of digits is Y(= 6) are:
501 = 5 + 0 + 1 = 6
510 = 5 + 1 + 0 = 6
600 = 6 + 0 + 0 = 6
Therefore, the required output is 3.
Input: L = 20, R = 10000, Y = 14
Naive Approach: Refer to previous post to solve this problem by iterating over all the numbers in the range [L, R], and for every number, check if its sum of digits is equal to Y or not. If found to be true, then increment the count. Finally, print the count obtained.
Time Complexity: O(R – L + 1) * log10(R)
Auxiliary Space: O(1)
Efficient approach: To optimize the above approach, the idea is to use Digit DP using the following recurrence relation:
where, sum: Represents sum of digits.
tight: Check if sum of digits exceed Y or not.
end: Stores the maximum possible value of ith digit of a number.
cntNum(N, Y, tight): Returns the count of numbers in the range [0, X] whose sum of digits is Y.
Before moving into the DP solution, it is good practice to write down the recursive code.
Here is the recursive code –
Follow the steps below to solve the problem using DP.
- Initialize a 3D array dp[N][Y][tight] to compute and store the values of all subproblems of the above recurrence relation.
- Finally, return the value of dp[N][sum][tight].
Below is the implementation of the above approach:
Time Complexity: O(Y * log10(R) * 10)
Auxiliary Space: O(Y * log10(R)