Problem Description
Given a non-negative integer n, count all numbers x with unique digits such that 0 <= x < 10^n. This involves ensuring that no digit repeats within a number.
Key Insights
- Use combinatorial counting to determine the number of valid numbers of a given digit length.
- For numbers with more than one digit, the first digit cannot be zero.
- For each additional digit, the choices decrease because digits must remain unique.
- The solution adds up valid counts for each possible digit length from 1 to n, plus the number 0.
Space and Time Complexity
Time Complexity: O(n) per computation since we iterate at most 10 times (n <= 8). Space Complexity: O(1) as only a few variables are used.
Solution
The solution uses a combinatorial approach. For n = 0, the answer is 1 (only number 0). For n >= 1, the solution counts valid numbers for each digit length k (1 <= k <= n):
- For 1-digit numbers, there are 9 possibilities (1-9).
- For k-digit numbers (k > 1), the first digit has 9 possibilities (1-9), and each subsequent digit has a decreasing number of available digits (from 10 minus the number already used). Specifically, for the second digit there are 9 choices, for the third digit there are 8, and so forth.
- Sum the counts for each valid digit length and add 1 for the number 0. This approach avoids generating all numbers and leverages basic combinatorial principles for an efficient count.