Find smallest number with given number of digits and sum of digits
Pattern: Candy and assign cookies
To make the smallest number with d digits summing to s, keep the big digits at the end. Reserve 1 for the first digit, fill from the right with 9s while possible, and put what is left (plus the reserved 1) at the front. Impossible if s > 9 × d, or s = 0 with more than one digit.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return the smallest number with exactly d digits (no leading zero) whose digits add up to s, as a string, or "-1"
if there is none. s = 9, d = 2 gives "18"; s = 20, d = 3 gives "299"; s = 0, d = 1 gives "0". The catalogue has no practice link for this one.
Think first
- Which digit position should be as small as possible?
- Where should the big digits go?
- What must the first digit be at least?
Hints
Brute force, and why it fails
Try every d-digit number: O(10ᵈ).
The key insight
Making the left digits small means pushing as much of the sum as possible to the right, which is filling with 9s from the right.
Dry run
| left | 19 |
|---|
s = 20, d = 3. Reserve 1 for the front: 19 left.
The plan
if s > 9d or (s == 0 and d > 1): return "-1"
s -= 1
for i from d - 1 down to 1: digit[i] = min(9, s); s -= digit[i]
digit[0] = s + 1
Complexity
- Time
O(d)- Space
O(d)
One pass over the digits.
Edge cases
- s = 0, d = 1: "0".
- s = 9d: all 9s.
- s = 1: 1 followed by zeros.
I've built my logic, show the code
Java
class Solution {
public String smallestNumber(int s, int d) {
if (s > 9 * d || (s == 0 && d > 1)) return "-1"; // too big, or only zeros with a leading zero
char[] out = new char[d];
s -= 1; // keep 1 back so the first digit is at least 1
for (int i = d - 1; i > 0; i--) { // fill from the right, as much as possible each time
int digit = Math.min(9, s);
out[i] = (char) ('0' + digit);
s -= digit;
}
out[0] = (char) ('0' + s + 1);
return new String(out);
}
}C++
class Solution {
public:
string smallestNumber(int s, int d) {
if (s > 9 * d || (s == 0 && d > 1)) return "-1"; // too big, or only zeros with a leading zero
string out(d, '0');
s -= 1; // keep 1 back so the first digit is at least 1
for (int i = d - 1; i > 0; i--) { // fill from the right, as much as possible each time
int digit = min(9, s);
out[i] = static_cast<char>('0' + digit);
s -= digit;
}
out[0] = static_cast<char>('0' + s + 1);
return out;
}
};Python
class Solution:
def smallestNumber(self, s: int, d: int) -> str:
if s > 9 * d or (s == 0 and d > 1):
return "-1" # too big, or only zeros with a leading zero
digits = [0] * d
s -= 1 # keep 1 back so the first digit is at least 1
for i in range(d - 1, 0, -1): # fill from the right, as much as possible each time
digits[i] = min(9, s)
s -= digits[i]
digits[0] = s + 1
return "".join(map(str, digits))Common mistakes
- Forgetting to reserve the 1 for the first digit, giving a leading zero.
- Filling from the left.