Numbers At Most N Given Digit Set - Problem
Digital Number Building Challenge

Imagine you have a special calculator that only has certain digit buttons working! Given an array of digits sorted in non-decreasing order, you can create numbers by pressing these buttons as many times as you want.

For example, if your working digits are ['1','3','5'], you could create numbers like:
'1', '3', '5' (single digits)
'13', '31', '55' (two digits)
'135', '311', '555' (three digits)
• And so on...

Your Mission: Count how many positive integers you can generate that are less than or equal to a given integer n.

This is a classic combinatorial counting problem that tests your understanding of digit manipulation and mathematical reasoning!

Input & Output

example_1.py — Basic Case
$ Input: digits = ['1','3','5'], n = 100
Output: 20
💡 Note: We can form: 1-digit (1,3,5), 2-digit (11,13,15,31,33,35,51,53,55), 3-digit (all combinations except those > 100). Total = 3 + 9 + 8 = 20.
example_2.py — Small Limit
$ Input: digits = ['1','4','9'], n = 1000000000
Output: 29523
💡 Note: With digits [1,4,9] and large n, we count all combinations systematically: 1-digit (3), 2-digit (9), 3-digit (27), ..., up to 10-digit numbers.
example_3.py — Edge Case
$ Input: digits = ['7'], n = 8
Output: 1
💡 Note: Only digit 7 available. We can only form the number 7, which is ≤ 8. Numbers like 77, 777 are all > 8.

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
135135135Target: ≤ 315Current: 315 ✓1-digit:3 wins2-digit:9 wins3-digit:Count bydigit rules
Understanding the Visualization
1
Count Short Wins
All combinations with fewer reels than n automatically win
2
Same Length Analysis
For same number of reels, check reel by reel from left to right
3
Constraint Tracking
Once a reel shows a digit less than n's digit, all following reels are free
4
Mathematical Sum
Add up all valid combinations without spinning every possibility
Key Takeaway
🎯 Key Insight: Mathematical counting avoids generating every number. Count shorter lengths (always valid) + same length (digit-by-digit comparison) = O(log n) solution!
Asked in
Google 45 Amazon 38 Apple 22 Microsoft 18
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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