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
Numbers At Most N Given Digit Set INPUT digits array: '1' '3' '5' [0] [1] [2] Target: n = 100 Example valid numbers: 1, 3, 5, 11, 13, 15, 31, 33, 35, 51, 53, 55... d = 3 digits available n has 3 digits (100) ALGORITHM STEPS 1 Count shorter numbers 1-digit: 3^1 = 3 2-digit: 3^2 = 9 Subtotal: 12 2 Count same-length nums n=100 has 3 digits Process digit by digit 3 Digit analysis (100) Pos 0: digits < '1': 0 Pos 1: digits < '0': 0 No 3-digit nums <= 100 4 Check exact match 100 cannot be formed (0 not in digits) Total = d^1 + d^2 + ... + d^(k-1) + same-length count FINAL RESULT Count Breakdown: 1-digit numbers: 3 2-digit numbers: 9 3-digit numbers <= 100: 8 TOTAL: 20 3-digit valid: 11,13,15,31, 33,35,51,53 (8 total) Output: 20 [OK] Verified correct! Key Insight: Use Mathematical Counting: For k-digit n with d available digits, count all numbers with fewer digits (d^1 + d^2 + ... + d^(k-1)), then carefully count k-digit numbers by analyzing each position. At each digit position, count how many valid digits are strictly smaller, then handle equal cases recursively. TutorialsPoint - Numbers At Most N Given Digit Set | Mathematical Counting Approach
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~35 min Avg. Time
856 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