FastPrepSmallest Number With a Given Digit Sum
Problems/Smallest Number With a Given Digit Sum

Smallest Number With a Given Digit Sum

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report gives the target construction but not the callable interface, valid-input guarantee, or examples. This practice version assumes that a solution exists and returns its decimal representation; the judged core task matches the report at about 94%.

Given integers digitSum and numberOfDigits, construct the smallest non-negative decimal number that:

  • has exactly numberOfDigits digits, and
  • has digits whose sum is exactly digitSum.

Return the number as a string. The first digit cannot be zero unless numberOfDigits is 1. The input is guaranteed to admit at least one valid number.

Function

smallestNumberWithDigitSum(digitSum: int, numberOfDigits: int) → String

Examples

Example 1

digitSum = 20numberOfDigits = 3return = "299"

The smallest three-digit number with digit sum 20 is 299. Any smaller hundreds digit would leave more than 18 for the final two digits.

Example 2

digitSum = 1numberOfDigits = 4return = "1000"

The leading digit must be nonzero, so 1000 is the smallest four-digit number with digit sum 1.

Constraints

  • 1 <= numberOfDigits.
  • 0 <= digitSum <= 9 * numberOfDigits.
  • If numberOfDigits is greater than 1, then digitSum is positive.
  • The returned string has exactly numberOfDigits characters and no leading zero.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public String smallestNumberWithDigitSum(int digitSum, int numberOfDigits) {
        // Write your code here.
    }
}
Checking account…