Count Numbers with Unique Digits - Problem
Given an integer n, return the count of all numbers with unique digits, x, where 0 ≤ x < 10n.
A number has unique digits if no digit appears more than once. For example, 123 has unique digits, but 112 does not because the digit 1 appears twice.
Examples:
- When
n = 2, we need to count numbers from0to99with unique digits - Numbers like
0, 1, 2, ..., 9, 10, 12, 13, ..., 98are valid (unique digits) - Numbers like
11, 22, 33, 44, 55, 66, 77, 88, 99are invalid (repeated digits)
This problem combines combinatorics and dynamic programming concepts to efficiently count valid numbers without generating them all.
Input & Output
example_1.py — Basic Case
$
Input:
n = 2
›
Output:
91
💡 Note:
For n=2, we count numbers 0-99. Single digits (0-9): 10 numbers. Two-digit numbers with unique digits: 9×9=81 (first digit 1-9, second digit can be 0-9 except first). Total: 10 + 81 = 91.
example_2.py — Minimum Case
$
Input:
n = 0
›
Output:
1
💡 Note:
For n=0, the range is [0, 10^0) = [0, 1), which contains only the number 0. Since 0 has unique digits (trivially), the answer is 1.
example_3.py — Edge Case
$
Input:
n = 1
›
Output:
10
💡 Note:
For n=1, we count numbers 0-9. All single-digit numbers have unique digits by definition. So the answer is 10.
Visualization
Tap to expand
Understanding the Visualization
1
Count by length
Separate plates by number of digits (1-digit, 2-digit, etc.)
2
Apply constraints
First position: 9 choices (1-9), can't start with 0
3
Permutation math
Each subsequent position has one fewer choice
4
Sum all cases
Add up valid combinations for all digit lengths
Key Takeaway
🎯 Key Insight: Mathematical counting using permutations is exponentially faster than brute force generation and checking.
Time & Space Complexity
Time Complexity
O(n)
We calculate the result for each digit length from 1 to n, each taking O(1) time
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to store intermediate calculations
✓ Linear Space
Constraints
- 0 ≤ n ≤ 8
- For n > 10, the answer would be the same as n = 10 since we only have 10 unique digits (0-9)
- Note: The maximum meaningful value is n = 10
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code