VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-smallest-number-with-given-number-of-digits-and-digit-sum/

⇱ Smallest number with given digit count and sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest number with given digit count and sum

Last Updated : 24 Mar, 2025

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.

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

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".


Output
18

[Expected Approach] Using Greedy Technique - O(d) Time and O(1) Space

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:

  • Check constraints to ensure a valid sum s can be formed using d digits, otherwise return "-1".
  • Initialize result as a string of d '0's and reserve 1 for the leftmost digit by reducing s by 1.
  • Traverse from right to left and place the largest possible digit (<= 9) while updating s accordingly.
  • If s <= 9, place its value at the current position and set s = 0 to stop further updates.
  • Assign the leftmost digit by adding the remaining s to ensure it remains non-zero.
  • Convert the result string to the required format and return it as the final output.

Output
18
Comment
Article Tags:
Article Tags: