Count Special Integers - Problem

We call a positive integer special if all of its digits are distinct.

Given a positive integer n, return the number of special integers that belong to the interval [1, n].

A special integer has no repeated digits. For example, 123 is special, but 112 is not special because digit 1 appears twice.

Input & Output

Example 1 — Small Range
$ Input: n = 20
Output: 18
💡 Note: Special integers from 1 to 20: 1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20. We exclude 11 because digit 1 repeats. All other numbers have distinct digits.
Example 2 — Single Digit
$ Input: n = 5
Output: 5
💡 Note: All numbers from 1 to 5 have distinct digits: 1,2,3,4,5. Each single-digit number is automatically special.
Example 3 — Edge Case
$ Input: n = 100
Output: 90
💡 Note: Includes all 1-digit (9) and 2-digit numbers with distinct digits (9×9=81), but excludes 100 because it has repeated 0s. Total: 9 + 81 = 90.

Constraints

  • 1 ≤ n ≤ 2 × 109

Visualization

Tap to expand
Count Special Integers Dynamic Programming Approach INPUT Range: [1, n] 1 20 Special vs Non-Special 123 Special (OK) 112 Not Special Input Value n = 20 Count special in [1, 20] ALGORITHM STEPS 1 Digit DP Setup Convert n=20 to digits [2,0] 2 Count Smaller Length 1-digit specials: 9 (1-9) 3 Count Same Length 2-digit: track used digits 4 Sum Results Total = 9 + 9 = 18 Counting Process 1-digit: 1,2,3...9 = 9 2-digit (10-19): 10,12,13,14,15,16,17,18,19 = 9 special numbers 20 has distinct digits! FINAL RESULT Special integers in [1, 20]: 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 11 11 is NOT special Output 18 18 special integers found in range [1, 20] Key Insight: Digit DP efficiently counts special integers by tracking which digits have been used. For n=20: Count all 1-digit numbers (9), then 2-digit numbers with distinct digits (10-20 except 11). Use bitmask to track used digits: each bit represents if digit 0-9 is used. Time: O(digits * 2^10) TutorialsPoint - Count Special Integers | DP Approach
Asked in
Google 15 Amazon 8 Microsoft 6
23.5K Views
Medium Frequency
~35 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