1.
Introduction
2.
Problem Statement
3.
Approach 1
4.
Program
4.1.
Input
4.2.
Output
4.3.
Time Complexity
4.4.
Space Complexity
5.
Approach 2
6.
Program
6.1.
Input
6.2.
Output
6.3.
Time Complexity
6.4.
Space Complexity
7.
Key Takeaways
Last Updated: Mar 27, 2024

# Count of numbers from the range [L, R] whose sum of digits is Y

Husen Kagdi
1 upvote

## Introduction

There will be a weekly contest this Sunday on the Leetcode platform. The tourist aka Gennady Korotkevich is preparing the problem statements for the contest. He thoughts of a problem namely the count of numbers from the range [L, R] whose sum of digits is Y. Let us discuss the problem statement and the various approaches to solve the problem.

## Problem Statement

Given two numbers â€˜Lâ€™ and â€˜Râ€™, we need to find the count of numbers between L and R, the the the whose sum of digits is â€˜Yâ€™.

For Example:

L=10, R=100, Y=7

Then the numbers whose sum of digits is 7 and lies between L and R are:

So there are 7 such numbers. Therefore the output is 7.

Also see, Euclid GCD Algorithm

## Approach 1

This is the brute force approach. The algorithm is as follows:

1. Iterate from i = L to i = R.
2. Initialize the answer as 0.
3. Calculate the sum of digits of â€˜iâ€™.
4. If the sum of digits is equal to â€˜Yâ€™, increment the answer.

Now let us implement it in the C++ programming language.

## Program

### Time Complexity

O((R - L) * log(R))

We are iterating from L and R and checking if the sum of digits of the iterator is equal to Y or not. The checking function takes O(log(R)) time in the worst case. The number is reduced to 1 by repeatedly dividing by 10. So it takes O( log(R) ) time.

### Space Complexity

O(1)

We are only declaring a fixed number of variables. So it takes constant space.

## Approach 2

cntNum(i, sum, tight) = i=09 cntNum(i+1, (sum - i), tight(i == end))

where sum denotes the total number of digits.

tight: Determine whether the total of the digits exceeds Y.

end: Stores the maximum potential value of a number's ith digit.

cntNum(N, Y, tight): cntNum(N, Y, tight):

Returns the number of numbers in the range [0, X] with a digit sum of Y.

Use DP to solve the problem by following the steps below.

1. To compute and store the values of all subproblems of the aforementioned recurrence relation, create a 3D array called dp[N][Y][tight].
2. Finally, dp[N][sum][tight] should be returned.

## Program

O( Y * log(R))

### Space Complexity

O( Y * log(R))

Check out this problem - Subarray Sum Divisible By K

## Key Takeaways

In this blog, we learned about a new problem namely the Count of numbers from the range [L, R] whose sum of digits is Y. We solved it using two different methods. The first method is Brute force and gives a time complexity of O((R - L+1) * log(R)). Second approach used dynamic programming and gave a time complexity of O(Y * log(R)). Stay tuned for more such problems.

Happy Coding!

Live masterclass