Smallest number with given digit count and sum

Last Updated : 16 Aug, 2026

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.

Try It Yourself
redirect icon

[Brute-Force Approach] Iterate Sequentially - O(d*(10^d)) time and O(1) Space

We iterate 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.

If no valid number exists, return "-1".

C++
// C++ program to find the smallest d-digit
// number with the given sum using
// a brute force approach
#include <bits/stdc++.h>
using namespace std;

string smallestNumber(int s, int d)
{

    // The smallest d-digit number is 10^(d-1)
    int start = pow(10, d - 1);

    // The largest d-digit number is 10^d - 1
    int end = pow(10, d) - 1;

    // Iterate through all d-digit numbers
    for (int num = start; num <= end; num++)
    {

        int sum = 0, x = num;

        // Calculate sum of digits
        while (x > 0)
        {
            sum += x % 10;
            x /= 10;
        }

        // If sum matches, return the number
        // as a string
        if (sum == s)
        {
            return to_string(num);
        }
    }

    // If no valid number is found, return "-1"
    return "-1";
}

// Driver Code
int main()
{

    int s = 9, d = 2;

    cout << smallestNumber(s, d) << endl;
    return 0;
}
Java
// Java program to find the smallest d-digit
// number with the given sum using
// a brute force approach
import java.util.*;

class GfG {

    static String smallestNumber(int s, int d)
    {

        // The smallest d-digit number is 10^(d-1)
        int start = (int)Math.pow(10, d - 1);

        // The largest d-digit number is 10^d - 1
        int end = (int)Math.pow(10, d) - 1;

        // Iterate through all d-digit numbers
        for (int num