oneby7

2-D Dynamic Programming Digit DP

603. Numbers At Most N Given Digit Set

Hard

You are given a list digits of distinct digits, each written as a one-character string, and a positive integer n. You may write a number using only digits from the list, and you may use each digit as many times as you like. For example, with digits = ["1","4"] you can write 4, 11, 41 and 1144.

Return how many positive integers that you can write this way are less than or equal to n.

Example 1

Input: digits = ["2", "5", "7"], n = 300

Output: 21

Explanation: There are 3 one-digit numbers (2, 5, 7) and 9 two-digit numbers, from 22 to 77. Of the three-digit numbers, only the 9 that start with 2 are below 300, from 222 to 277. That makes 3 + 9 + 9 = 21.

Example 2

Input: digits = ["1", "4", "9"], n = 1000

Output: 39

Explanation: Every number with one, two or three digits is below 1000, which gives 3 + 9 + 27 = 39. The smallest four-digit number you can write is 1111, and it is already too big.

Example 3

Input: digits = ["3", "8"], n = 838

Output: 12

Explanation: Lengths one and two give 2 + 4 = 6 numbers. The three-digit numbers up to 838 are 333, 338, 383, 388, 833 and 838, and 838 itself counts. That makes 12.

Check your understanding

Work out the answer for this input before you write any code.

digits = ["1", "2"], n = 21

Constraints

  • 1 ≤ digits.length ≤ 9
  • Each digits[i] is a single digit from "1" to "9".
  • The digits are distinct and sorted in increasing order.
  • 1 ≤ n ≤ 1015

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.