How to find the smallest number with given digit sum s and number of digits d?
Input : s = 9, d = 2 Output : 18 There are many other possible numbers like 45, 54, 90, etc with sum of digits as 9 and number of digits as 2. The smallest of them is 18. Input : s = 20, d = 3 Output : 299
A Simple Solution is to consider all m digit numbers and keep track of minimum number with digit sum as s. A close upper bound on time complexity of this solution is O(10m).
There is a Greedy approach to solve the problem. The idea is to one by one fill all digits from rightmost to leftmost (or from least significant digit to most significant).
We initially deduct 1 from sum s so that we have smallest digit at the end. After deducting 1, we apply greedy approach. We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits from right to left, we put the highest digits on the right side. Below is implementation of the idea.
Smallest number is 18
Time Complexity of this solution is O(m).
We will soon be discussing approach to find the largest possible number with given sum of digits and number of digits.
This article is contributed by Vaibhav Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find smallest number with given number of digits and sum of digits under given constraints
- Find smallest possible Number from a given large Number with same count of digits
- Find the smallest number whose digits multiply to a given number n
- Smallest number with given sum of digits and sum of square of digits
- Find the smallest positive number which can not be represented by given digits
- Find the Largest number with given number of digits and sum of digits
- Smallest odd digits number not less than N
- Smallest even digits number not less than N
- Immediate smallest number after re-arranging the digits of a given number
- Smallest number by rearranging digits of a given number
- Smallest number with sum of digits as N and divisible by 10^N
- Smallest number k such that the product of digits of k is equal to n
- Smallest multiple of a given number made of digits 0 and 9 only
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Smallest number greater than or equal to X whose sum of digits is divisible by Y