Skip to content

902. Numbers At Most N Given Digit Set

Description

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.

 

Example 1:

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.

Example 2:

Input: digits = ["1","4","9"], n = 1000000000
Output: 29523
Explanation: 
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits array.

Example 3:

Input: digits = ["7"], n = 8
Output: 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

Solutions

Solution 1: Digit DP

This problem is essentially asking for the count of positive integers generated by the numbers in digits within the given range $[l,..r]$. The count is related to the number of digits and the digit at each position. We can use the idea of Digit DP to solve this problem. In Digit DP, the size of the number has a small impact on the complexity.

For the range $[l,..r]$, we generally convert it into $[1,..r]$ and then subtract $[1,..l - 1]$, i.e.,

$$ ans = \sum_{i=1}^{r} ans_i - \sum_{i=1}^{l-1} ans_i $$

However, for this problem, we only need to calculate the value of the range $[1,..r]$.

Here we use memoization search to implement Digit DP. We search from the starting point to the bottom layer to get the number of schemes, return the answer layer by layer and accumulate it, and finally get the final answer from the starting point of the search.

The basic steps are as follows:

  1. Convert the number $n$ into an int array $a$, where $a[1]$ is the lowest digit and $a[len]$ is the highest digit;
  2. Design the function $dfs()$ based on the problem information. For this problem, we define $dfs(pos, lead, limit)$, and the answer is $dfs(len, 1, true)$.

Where:

  • pos represents the number of digits in the number, starting from the last digit or the first digit, usually chosen based on the digit construction property of the problem. For this problem, we choose to start from the high digit, so the initial value of pos is len;
  • lead indicates whether the current number contains leading zeros. If it does, it is 1, otherwise it is 0. It is initialized to 1;
  • limit represents the restriction on the digits that can be filled. If there is no restriction, you can choose $[0,1,..9]$, otherwise, you can only choose $[0,..a[pos]]$. If limit is true and the maximum value that can be taken has been taken, then the next limit is also true. If limit is true but the maximum value has not been taken, or if limit is false, then the next limit is false.

For the implementation details of the function, you can refer to the code below.

The time complexity is $O(\log n)$.

Similar problems:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:
        @cache
        def dfs(pos, lead, limit):
            if pos <= 0:
                return lead == False
            up = a[pos] if limit else 9
            ans = 0
            for i in range(up + 1):
                if i == 0 and lead:
                    ans += dfs(pos - 1, lead, limit and i == up)
                elif i in s:
                    ans += dfs(pos - 1, False, limit and i == up)
            return ans

        l = 0
        a = [0] * 12
        s = {int(d) for d in digits}
        while n:
            l += 1
            a[l] = n % 10
            n //= 10
        return dfs(l, True, True)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
    private int[] a = new int[12];
    private int[][] dp = new int[12][2];
    private Set<Integer> s = new HashSet<>();

    public int atMostNGivenDigitSet(String[] digits, int n) {
        for (var e : dp) {
            Arrays.fill(e, -1);
        }
        for (String d : digits) {
            s.add(Integer.parseInt(d));
        }
        int len = 0;
        while (n > 0) {
            a[++len] = n % 10;
            n /= 10;
        }
        return dfs(len, 1, true);
    }

    private int dfs(int pos, int lead, boolean limit) {
        if (pos <= 0) {
            return lead ^ 1;
        }
        if (!limit && lead != 1 && dp[pos][lead] != -1) {
            return dp[pos][lead];
        }
        int ans = 0;
        int up = limit ? a[pos] : 9;
        for (int i = 0; i <= up; ++i) {
            if (i == 0 && lead == 1) {
                ans += dfs(pos - 1, lead, limit && i == up);
            } else if (s.contains(i)) {
                ans += dfs(pos - 1, 0, limit && i == up);
            }
        }
        if (!limit && lead == 0) {
            dp[pos][lead] = ans;
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
    int a[12];
    int dp[12][2];
    unordered_set<int> s;

    int atMostNGivenDigitSet(vector<string>& digits, int n) {
        memset(dp, -1, sizeof dp);
        for (auto& d : digits) {
            s.insert(stoi(d));
        }
        int len = 0;
        while (n) {
            a[++len] = n % 10;
            n /= 10;
        }
        return dfs(len, 1, true);
    }

    int dfs(int pos, int lead, bool limit) {
        if (pos <= 0) {
            return lead ^ 1;
        }
        if (!limit && !lead && dp[pos][lead] != -1) {
            return dp[pos][lead];
        }
        int ans = 0;
        int up = limit ? a[pos] : 9;
        for (int i = 0; i <= up; ++i) {
            if (i == 0 && lead) {
                ans += dfs(pos - 1, lead, limit && i == up);
            } else if (s.count(i)) {
                ans += dfs(pos - 1, 0, limit && i == up);
            }
        }
        if (!limit && !lead) {
            dp[pos][lead] = ans;
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
func atMostNGivenDigitSet(digits []string, n int) int {
    s := map[int]bool{}
    for _, d := range digits {
        i, _ := strconv.Atoi(d)
        s[i] = true
    }
    a := make([]int, 12)
    dp := make([][2]int, 12)
    for i := range a {
        dp[i] = [2]int{-1, -1}
    }
    l := 0
    for n > 0 {
        l++
        a[l] = n % 10
        n /= 10
    }
    var dfs func(int, int, bool) int
    dfs = func(pos, lead int, limit bool) int {
        if pos <= 0 {
            return lead ^ 1
        }
        if !limit && lead == 0 && dp[pos][lead] != -1 {
            return dp[pos][lead]
        }
        up := 9
        if limit {
            up = a[pos]
        }
        ans := 0
        for i := 0; i <= up; i++ {
            if i == 0 && lead == 1 {
                ans += dfs(pos-1, lead, limit && i == up)
            } else if s[i] {
                ans += dfs(pos-1, 0, limit && i == up)
            }
        }
        if !limit {
            dp[pos][lead] = ans
        }
        return ans
    }
    return dfs(l, 1, true)
}

Comments