Count Numbers With Unique Digits II - Problem
Given two positive integers a and b, your task is to count how many numbers in the range [a, b] (inclusive) have unique digits. A number has unique digits if no digit appears more than once in its decimal representation.

For example, the number 123 has unique digits because each digit (1, 2, 3) appears only once. However, 1223 does not have unique digits because the digit 2 appears twice.

Goal: Return the count of numbers with unique digits in the given range.

Input: Two positive integers a and b where a โ‰ค b
Output: An integer representing the count of numbers with unique digits in range [a, b]

Input & Output

example_1.py โ€” Basic Range
$ Input: a = 1, b = 20
โ€บ Output: 19
๐Ÿ’ก Note: All numbers from 1-20 have unique digits except 11 (digit 1 repeats). Numbers with unique digits: 1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20.
example_2.py โ€” Small Range
$ Input: a = 80, b = 120
โ€บ Output: 27
๐Ÿ’ก Note: In range [80,120], numbers like 88, 99, 100, 110, 111, etc. have repeated digits. Only numbers with all unique digits are counted.
example_3.py โ€” Single Number
$ Input: a = 123, b = 123
โ€บ Output: 1
๐Ÿ’ก Note: Only checking number 123, which has digits 1, 2, 3 - all unique, so count is 1.

Constraints

  • 1 โ‰ค a โ‰ค b โ‰ค 108
  • The range [a, b] will contain at most 106 numbers
  • Time limit: 2 seconds

Visualization

Tap to expand
Digit Uniqueness Scanner ProcessInput Range[a, b]Digit ScannerProcess Each #Valid CountUnique DigitsExample: Scanning Number 12344321โ†’All Unique โœ“Boolean Array: [F,T,T,T,T,F,F,F,F,F] - digits 1,2,3,4 marked as seenCounter Example: Scanning Number 11233211โ†’Duplicate Found โœ—
Understanding the Visualization
1
Number Processing
Each number passes through our digit scanner
2
Digit Extraction
Scanner extracts each digit one by one
3
Duplicate Detection
Boolean array tracks which digits we've seen
4
Immediate Rejection
If duplicate found, reject immediately
5
Count Valid
Only numbers with unique digits pass through
Key Takeaway
๐ŸŽฏ Key Insight: Using a boolean array to track seen digits allows O(1) duplicate detection per digit, making the algorithm efficient while processing each number in the range.
Asked in
Google 42 Amazon 35 Microsoft 28 Apple 22
42.6K Views
Medium Frequency
~15 min Avg. Time
1.6K 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