866. Numbers From a Digit Set

A cash register's keypad has had most of its keys removed, and only the digit keys listed in digits still work. The list holds distinct one-character strings from "1" to "9", sorted in increasing order. A clerk can press the working keys any number of times (each key may be reused freely) to type a positive whole number with no leading zeros.

Return how many different positive integers that are less than or equal to n can be typed using only the working keys. Typing every candidate is infeasible for large n, so count by length and by digit position instead.

Example 1

Input:
digits = ["2","5"], n = 60
Output:
6
Explanation:

The numbers up to 60 written only with 2 and 5 are 2, 5, 22, 25, 52, 55, so there are 6.

Example 2

Input:
digits = ["1","4","7"], n = 50
Output:
9
Explanation:

The numbers up to 50 written only with 1, 4 and 7 are 1, 4, 7, 11, 14, 17, 41, 44, 47, which is 9 numbers.

Constraints

  • 1 ≤ digits.length ≤ 9
  • digits[i] is a character from '1' to '9', strictly increasing
  • 1 ≤ n ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(L log D)
Space
O(L)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…