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.

Examples

Example 1

1
2
3
4
5
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

1
2
3
4
5
6
7
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

1
2
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 <= 10^9

Solution

Method 1 – Digit DP (Dynamic Programming on Digits)

Intuition

We count numbers less than or equal to n by considering two cases: numbers with fewer digits than n, and numbers with the same number of digits as n. For the latter, we use digit-by-digit DP, ensuring we do not exceed n at any position.

Approach

  1. For numbers with fewer digits than n, count all possible numbers: for each length l < len(str(n)), total is len(digits)^l.
  2. For numbers with the same number of digits as n:
    • Traverse each digit position, for each digit in digits less than n’s current digit, count all combinations for the remaining positions.
    • If a digit matches n’s current digit, continue to next position (tight bound).
    • If no digit matches, break.
  3. Sum both cases for the answer.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int atMostNGivenDigitSet(vector<string>& digits, int n) {
        string s = to_string(n);
        int k = s.size(), ans = 0, D = digits.size();
        for (int i = 1; i < k; ++i) ans += pow(D, i);
        for (int i = 0; i < k; ++i) {
            bool same = false;
            for (auto& d : digits) {
                if (d[0] < s[i]) ans += pow(D, k-i-1);
                else if (d[0] == s[i]) same = true;
            }
            if (!same) return ans;
        }
        return ans + 1;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
func atMostNGivenDigitSet(digits []string, n int) int {
    s := strconv.Itoa(n)
    k, D := len(s), len(digits)
    ans := 0
    for i := 1; i < k; i++ {
        ans += int(math.Pow(float64(D), float64(i)))
    }
    for i := 0; i < k; i++ {
        same := false
        for _, d := range digits {
            if d[0] < s[i] {
                ans += int(math.Pow(float64(D), float64(k-i-1)))
            } else if d[0] == s[i] {
                same = true
            }
        }
        if !same {
            return ans
        }
    }
    return ans + 1
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int atMostNGivenDigitSet(String[] digits, int n) {
        String s = String.valueOf(n);
        int k = s.length(), D = digits.length, ans = 0;
        for (int i = 1; i < k; ++i) ans += Math.pow(D, i);
        for (int i = 0; i < k; ++i) {
            boolean same = false;
            for (String d : digits) {
                if (d.charAt(0) < s.charAt(i)) ans += Math.pow(D, k-i-1);
                else if (d.charAt(0) == s.charAt(i)) same = true;
            }
            if (!same) return ans;
        }
        return ans + 1;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    fun atMostNGivenDigitSet(digits: Array<String>, n: Int): Int {
        val s = n.toString()
        val k = s.length
        val D = digits.size
        var ans = 0
        for (i in 1 until k) ans += Math.pow(D.toDouble(), i.toDouble()).toInt()
        for (i in 0 until k) {
            var same = false
            for (d in digits) {
                if (d[0] < s[i]) ans += Math.pow(D.toDouble(), (k-i-1).toDouble()).toInt()
                else if (d[0] == s[i]) same = true
            }
            if (!same) return ans
        }
        return ans + 1
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def atMostNGivenDigitSet(self, digits: list[str], n: int) -> int:
        s = str(n)
        k, D = len(s), len(digits)
        ans = 0
        for i in range(1, k):
            ans += D ** i
        for i in range(k):
            same = False
            for d in digits:
                if d < s[i]:
                    ans += D ** (k-i-1)
                elif d == s[i]:
                    same = True
            if not same:
                return ans
        return ans + 1
 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
impl Solution {
    pub fn at_most_n_given_digit_set(digits: Vec<String>, n: i32) -> i32 {
        let s = n.to_string();
        let k = s.len();
        let d = digits.len();
        let mut ans = 0;
        for i in 1..k {
            ans += d.pow(i as u32) as i32;
        }
        for (i, c) in s.chars().enumerate() {
            let mut same = false;
            for dd in &digits {
                let dc = dd.chars().next().unwrap();
                if dc < c {
                    ans += d.pow((k-i-1) as u32) as i32;
                } else if dc == c {
                    same = true;
                }
            }
            if !same {
                return ans;
            }
        }
        ans + 1
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    atMostNGivenDigitSet(digits: string[], n: number): number {
        const s = n.toString();
        const k = s.length, D = digits.length;
        let ans = 0;
        for (let i = 1; i < k; ++i) ans += Math.pow(D, i);
        for (let i = 0; i < k; ++i) {
            let same = false;
            for (const d of digits) {
                if (d < s[i]) ans += Math.pow(D, k-i-1);
                else if (d === s[i]) same = true;
            }
            if (!same) return ans;
        }
        return ans + 1;
    }
}

Complexity

  • ⏰ Time complexity: O(k * D) — k is the number of digits in n, D is the number of digits in the set.
  • 🧺 Space complexity: O(1) — Only a few counters and variables are used.