#2376
Count Special Integers
HardMathDynamic ProgrammingDynamic ProgrammingBitmasking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use digit dynamic programming to count special integers more efficiently by building numbers with distinct digits and using a bitmask to track used digits.
⚙️
Algorithm
4 steps- 1Step 1: Convert n to a string to analyze its digits.
- 2Step 2: Use a recursive function with memoization to count valid numbers with distinct digits, considering the current position, the used digits, and whether we are still bound by n.
- 3Step 3: Count all valid numbers with fewer digits than n.
- 4Step 4: Count valid numbers with the same number of digits as n, ensuring they do not exceed n.
solution.py28 lines
1# Full working Python code
2
3def count_special_integers(n):
4 s = str(n)
5 length = len(s)
6 dp = [[-1] * (1 << 10) for _ in range(length + 1)]
7
8 def dfs(pos, mask, tight):
9 if pos == length:
10 return 1
11 if dp[pos][mask] != -1:
12 return dp[pos][mask]
13 limit = int(s[pos]) if tight else 9
14 count = 0
15 for digit in range(0, limit + 1):
16 if mask & (1 << digit) == 0:
17 count += dfs(pos + 1, mask | (1 << digit), tight and (digit == limit))
18 dp[pos][mask] = count
19 return count
20
21 total = 0
22 for i in range(1, length):
23 total += 9 * (9 ** (i - 1)) # Count numbers with fewer digits
24 total += dfs(0, 0, True) # Count numbers with the same number of digits
25 return total
26
27# Example usage
28print(count_special_integers(20))ℹ
Complexity note: The time complexity is O(n) due to the digit dynamic programming approach, which efficiently counts valid numbers without generating them all.
- 1Distinct digits are crucial for a number to be special.
- 2Using dynamic programming can significantly reduce computation time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.