Numbers At Most N Given Digit Set - Problem
Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want.
For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the number of positive integers that can be generated that are less than or equal to a given integer n.
Input & Output
Example 1 — Basic Case
$
Input:
digits = ["1","3","5"], n = 100
›
Output:
20
💡 Note:
1-digit: 1,3,5 (count=3). 2-digit: 11,13,15,31,33,35,51,53,55 (count=9). 3-digit: 111,113,115,131,133,135,151,153,155 (count=8). Total = 3+9+8 = 20
Example 2 — Single Digit
$
Input:
digits = ["1","4","9"], n = 1000000000
›
Output:
29523
💡 Note:
Count systematically: 1-digit (3), 2-digit (9), 3-digit (27), ..., up to 9-digit numbers, plus valid 10-digit numbers ≤ 1000000000
Example 3 — Small Target
$
Input:
digits = ["7"], n = 8
›
Output:
1
💡 Note:
Only digit 7 available. Only valid number ≤ 8 is 7 itself. Count = 1
Constraints
- 1 ≤ digits.length ≤ 9
- digits[i].length == 1
- digits[i] is a digit from '1' to '9'
- All the values in digits are unique
- digits is sorted in non-decreasing order
- 1 ≤ n ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
digits=['1','3','5'], n=100
2
Count by Length
1-digit: 3 numbers, 2-digit: 9 numbers, 3-digit: check constraints
3
Output
Total count = 20
Key Takeaway
🎯 Key Insight: Count by length groups first, then handle same-length numbers with digit-by-digit constraints
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code