Count Numbers with Unique Digits

You can solve this problem by using a dynamic programming approach. Here’s a simple Python function that calculates the count of all numbers with unique digits for a given n.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def countNumbersWithUniqueDigits(self, n: int) -> int:
        if n == 0:
            return 1

        dp = [0] * (n + 1)
        dp[0] = 1
        dp[1] = 10

        for i in range(2, n + 1):
            unique_digits = 9
            for j in range(9, 9 - i + 1, -1):
                unique_digits *= j
            dp[i] = unique_digits + dp[i - 1]

        return dp[n]

Here’s an explanation of the approach:

  • For n=0, there is only one number (0) with unique digits, so we return 1.
  • For n=1, we have 10 numbers with unique digits (from 0 to 9), so we return 10.
  • For larger values of n, we calculate the count of numbers with unique digits by multiplying the available choices for each digit position.
  • We keep track of the results using a dynamic programming table, and we return the result for the given n.