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
- 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 Largest number with given number of digits and sum of digits
- Smallest even digits number not less than N
- Smallest odd 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
- 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
- Minimum number of digits to be removed so that no two consecutive digits are same
- Find maximum number that can be formed using digits of a given number