FastPrepSmallest Number With a Given Digit Sum
Problem · Greedy

Smallest Number With a Given Digit Sum

Learn this problem
MediumAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

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

drafts saved locally
public String smallestNumberWithDigitSum(int digitSum, int numberOfDigits) {
    // Write your code here.
}
digitSum20
numberOfDigits3
expected"299"
checking account