![]() |
VOOZH | about |
Given two integers s and d, find the smallest possible number that has exactly d digits and a sum of digits equal to s.
Return the number as a string. If no such number exists, return "-1".
Examples :
Input: s = 9, d = 2
Output: 18
Explanation: 18 is the smallest number possible with the sum of digits = 9 and total digits = 2.Input: s = 20, d = 3
Output: 299
Explanation: 299 is the smallest number possible with the sum of digits = 20 and total digits = 3.Input: s = 1, d = 1
Output: 1
Explanation: 1 is the smallest number possible with the sum of digits = 1 and total digits = 1.
Table of Content
Since numbers are sequential, the brute force approach iterates from the smallest d-digit number to the largest, checking each one. For every number, we compute the sum of its digits and return the first valid match, ensuring the smallest possible number is selected. If no valid number exists, we return "-1".
18
The approach ensures the leftmost digit is non-zero, so we reserve 1 for it and distribute the remaining sum from right to left to form the smallest possible number. The greedy approach helps in placing the largest possible values (up to 9) at the rightmost positions to keep the number small.
Steps to implement the above idea:
18