Count Numbers With Unique Digits II - Problem

Given two positive integers a and b, return the count of numbers having unique digits in the range [a, b] (inclusive).

A number has unique digits if no digit appears more than once in the number. For example, 123 has unique digits, but 121 does not because the digit 1 appears twice.

Input & Output

Example 1 — Small Range
$ Input: a = 20, b = 25
Output: 5
💡 Note: Numbers 20, 21, 23, 24, 25 all have unique digits. Number 22 has repeated digit '2', so it's not counted.
Example 2 — Single Digits
$ Input: a = 1, b = 10
Output: 10
💡 Note: All single digit numbers (1-9) and 10 have unique digits. Total count is 10.
Example 3 — Range with Repeats
$ Input: a = 80, b = 120
Output: 27
💡 Note: Count numbers from 80-120 where all digits are unique. Excludes numbers like 88, 99, 100, 101, 110, 111, etc.

Constraints

  • 1 ≤ a ≤ b ≤ 108
  • Both a and b are positive integers

Visualization

Tap to expand
Count Numbers With Unique Digits II INPUT Range [a, b] 20 21 22 23 24 25 Unique digits Repeated digits Input Values a = 20 b = 25 6 numbers to check ALGORITHM STEPS 1 Initialize count = 0, hashmap = {} 2 For each num in [a,b] Extract digits of num 3 Check uniqueness Use hashmap to track digits HashMap Example (num=23): {2: 1, 3: 1} All counts = 1 --> Unique! 4 Increment count If unique, count++ FINAL RESULT Analysis of each number: 20: {2,0} --> Unique OK 21: {2,1} --> Unique OK 22: {2,2} --> NOT unique 23: {2,3} --> Unique OK 24: {2,4} --> Unique OK 25: {2,5} --> Unique OK OUTPUT 5 Key Insight: Hash Map tracks digit frequency in O(1) time. For each number, iterate through its digits and check if any digit appears more than once. If all digit counts are 1, the number has unique digits. TutorialsPoint - Count Numbers With Unique Digits II | Hash Map Optimization Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
23.5K Views
Medium Frequency
~15 min Avg. Time
890 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