Numbers At Most N Given Digit Set

Given a set of allowed digits and an integer n, return how many positive integers less than or equal to n can be formed using only the allowed digits. Pattern focus: Digit DP. Decide digit by digit while respecting the tight prefix constraint.

Input Format

digits = allowed digit strings, n = upper bound

Output Format

count of positive integers <= n formed using only digits

Constraints

  • 1 <= digits.length <= 9
  • Digits are distinct and between '1' and '9'
  • 1 <= n <= 10^9

Examples

Example 1:

Input:

digits = ["1","3","5","7"]
n = 100

Output:

20

Explanation:

There are 20 valid numbers that can be formed and are at most 100.

Example 2:

Input:

digits = ["1","4","9"]
n = 1

Output:

1

Explanation:

Only the number 1 is valid.

Example 3:

Input:

digits = ["7"]
n = 8

Output:

1

Explanation:

Only the number 7 can be formed.

Loading...
Numbers At Most N Given Digit Set - Dp Advanced