Leetcode #902: Numbers At Most N Given Digit Set
In this guide, we solve Leetcode #902 Numbers At Most N Given Digit Set in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, String, Binary Search, Dynamic Programming
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: digits = ["1","3","5","7"], n = 100
Output: 20
Explanation:
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
Python Solution
class Solution:
def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
def dfs(i: int, lead: int, limit: bool) -> int:
if i >= len(s):
return lead ^ 1
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
if j == 0 and lead:
ans += dfs(i + 1, 1, limit and j == up)
elif j in nums:
ans += dfs(i + 1, 0, limit and j == up)
return ans
s = str(n)
nums = {int(x) for x in digits}
return dfs(0, 1, True)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.