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 is repeated in the number. For example, 123 has unique digits but 121 does not.

Input & Output

Example 1 — Small Case
$ Input: n = 2
Output: 91
💡 Note: Count all numbers from 0 to 99 with unique digits: single digits (0-9) = 10, two-digits with unique digits (10,12,13,...,98) = 81. Total = 10 + 81 = 91
Example 2 — Minimal Case
$ Input: n = 0
Output: 1
💡 Note: Range is [0, 1), so only number 0 exists, which has unique digits
Example 3 — Larger Case
$ Input: n = 3
Output: 739
💡 Note: Numbers 0 to 999: 1-digit = 10, 2-digit = 81, 3-digit = 648. Total = 10 + 81 + 648 = 739

Constraints

  • 0 ≤ n ≤ 8

Visualization

Tap to expand
Count Numbers with Unique Digits INPUT n = 2 Number of digits Range: 0 to 10^n 0 <= x < 100 (0 to 99) Examples: 23 OK unique 11 NOT unique 0-9: all unique (10 nums) 10-99: count valid ones ALGORITHM STEPS 1 Base Case n=0: return 1 (just 0) 2 Count 1-digit: 10 0,1,2,3,4,5,6,7,8,9 3 Count 2-digit unique First digit: 9 choices Second: 9 choices 2-digit: 9 × 9 = 81 (1st: not 0, 2nd: not 1st) 4 Sum All Counts Total = 10 + 81 = 91 General Formula: k-digit: 9×9×8×7×...×(11-k) Sum from 1 to n digits FINAL RESULT Calculation for n=2: 1-digit numbers: 10 2-digit unique: 81 (9 × 9 = 81) Total: 91 Output: 91 OK - Verified! 91 numbers from 0-99 have all unique digits Key Insight: Use permutation counting: For k-digit numbers, first digit has 9 choices (1-9, not 0), second has 9 choices (0-9 minus first), third has 8, and so on. Sum counts for 1 to n digits. Time: O(n), Space: O(1) - No recursion or DP table needed, just multiplication! TutorialsPoint - Count Numbers with Unique Digits | Optimal Solution (Combinatorics)
Asked in
Google 25 Facebook 18
23.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen