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 firstname.lastname@example.org. 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
- 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 number by rearranging digits of a given number
- Immediate smallest number after re-arranging the digits of a given number
- Smallest odd digits number not less than N
- Smallest even digits number not less than N
- Smallest number with sum of digits as N and divisible by 10^N
- Smallest multiple of a given number made of digits 0 and 9 only
- Smallest number k such that the product of digits of k is equal to n
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Get the kth smallest number using the digits of the given number
- Check whether product of digits at even places is divisible by sum of digits at odd place of a number
- Maximize the given number by replacing a segment of digits with the alternate digits given