#902
Numbers At Most N Given Digit Set
HardArrayMathStringBinary SearchDynamic ProgrammingCombinatorial CountingDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the properties of the digits and the structure of the number n to count valid combinations without generating them. We use mathematical counting based on the length of n and the digits available.
⚙️
Algorithm
3 steps- 1Step 1: Count all numbers with fewer digits than n using the formula len(digits) ^ i for i from 1 to len(n) - 1.
- 2Step 2: For numbers with the same number of digits as n, iterate through each digit of n and count how many valid digits are less than the current digit.
- 3Step 3: If a digit matches, continue checking the next digit; if a digit is smaller, add the count of all combinations that can be formed with the remaining digits.
solution.py20 lines
1def atMostNGivenDigitSet(digits, n):
2 count = 0
3 n_str = str(n)
4 length_n = len(n_str)
5
6 # Count numbers with fewer digits than n
7 count += sum(len(digits) ** i for i in range(1, length_n))
8
9 # Count numbers with the same number of digits as n
10 for i in range(length_n):
11 found_smaller = False
12 for d in digits:
13 if d < n_str[i]:
14 count += len(digits) ** (length_n - i - 1)
15 elif d == n_str[i]:
16 found_smaller = True
17 break
18 if not found_smaller:
19 break
20 return countℹ
Complexity note: The time complexity is O(n) because we iterate through the digits of n, and for each digit, we check against the digits array, which is constant in size.
- 1Understanding how to count combinations efficiently is crucial.
- 2Recognizing the constraints of the problem helps in optimizing the approach.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.