Numbers At Most N Given Digit Set — LeetCode 902 Python Solution

HardArrayMathStringBinary SearchDynamic Programming
Problem
#902
Reading time
3 min

The 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.

Example

Input
digits = ["1","3","5","7"], n = 100
Output
20
Explanation
The 20 numbers that can be written are:

Python solution

Python
class Solution:
    def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
        @cache
        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

MeasureComplexity
TimeO(\log n \times D)
SpaceO(\log n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 902. Numbers At Most N Given Digit Set is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 902. Numbers At Most N Given Digit Set?
LeetCode 902. Numbers At Most N Given Digit Set is rated Hard on LeetCode.
What is the time complexity of LeetCode 902. Numbers At Most N Given Digit Set?
The Python solution on this page runs in O(\log n \times D).
What is the space complexity of LeetCode 902. Numbers At Most N Given Digit Set?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 902. Numbers At Most N Given Digit Set cover?
LeetCode 902. Numbers At Most N Given Digit Set is tagged Array, Math, String, Binary Search and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview