VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/

⇱ Count of n digit numbers with given digit sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of n digit numbers with given digit sum

Last Updated : 3 Jun, 2026

Given two integers n and sum, find the number of n-digit positive integers whose digits add up to sum.

  • An n-digit number cannot have leading zeros; that is, the first digit must be between 1 and 9.
  • If there exist no n digit number with sum of digits equal to given sum, return -1.

Example:

Input: n = 2, sum= 2
Output: 2
Explanation: The numbers are 11 and 20 .

Input: n = 1, sum = 10
Output: -1
Explanation: A single-digit number can only have a digit sum between 0 and 9.

Input: n = 2, sum= 5
Output: 5
Explanation: The numbers are 14, 23, 32, 41 and 50.

[Naive Approach - 1] - Recursively Try All - O(n*(9^n)) Time and O(n) Space

The idea is to use recursion to try every digit from 0 to 9 for each position, reducing the given sum at each step. The first digit is taken from 1 to 9 to ensure valid n-digit numbers. The recursion stops when there are no digits left, checking if the sumbecomes zero.


Output
5

[Naive Approach - 2] - Iteratively Try All - O(n*10^n) Time and O(1) Space

We iterate through each number within the range of n-digit numbers. For each number, we calculate the sum of its digits. If the sum matches the given sum, we increment the count.


Output
5

[Better Approach] - Memoization - O(n * sum) Time and O(n * sum) Space

The idea is to count n-digit numbers with a sum of digits equal to the given sum using recursion with memoization to optimize repeated calculations.

  • A 2d array memo[][] of size (n+1)x(sum+1) is used where memo[[i][j] denotes count of i digit numbers having sum j.
  • Starting from digits 1 to 9 for the first position, recursively explores all possible digits while reducing the given sum, ensuring efficiency by reusing previously computed results.

Output
5

[Expected Approach] - Tabulation - O(n * sum) Time and O(n * sum) Space

The idea is to build the answer in a bottom-up manner using dynamic programming. We create a 2D DP table where dp[len][s] stores the number of ways to form a digit sequence of length len whose digits add up to s.

  • We start with the base case dp[0][0] = 1, representing one way to achieve a sum of 0 using 0 digits.
  • Then, for each length and sum, we consider all possible digits from 0 to 9 and use previously computed states to update the current state.
  • By filling the table systematically, every subproblem is solved exactly once.
  • Since the first digit of an n-digit number cannot be 0, we choose the first digit from 1 to 9 and use the DP table to count the valid ways to form the remaining digits.

Output
5


Comment