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:
12
💡 Note:
1-digit: 1,3,5 (count=3). 2-digit: 11,13,15,31,33,35,51,53,55 (count=9). 3-digit ≤ 100: none (smallest 3-digit number possible is 111 > 100). Total = 3+9 = 12
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code