Count Special Integers Problem
#2376
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2376.
We call a positive integer special if all of its digits are distinct.
Given a positive integer n, return the number of special integers that belong to the interval [1, n].
Example 1:
Input: n = 20
Output: 19
Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
Example 2:
Input: n = 5
Output: 5
Explanation: All the integers from 1 to 5 are special.
Example 3:
Input: n = 135
Output: 110
Explanation: There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.
Constraints:
1 <= n <= 2 * 10^9
Solution
Approach: Digit DP
Write n as a string of digits and count numbers from 0 to n with no repeated digit. Let dfs(i, mask, lead, limit) process digit i, where mask is the set of used digits, lead says we are still in leading zeros (nothing placed yet), and limit says the prefix equals the prefix of n, so the digit is capped by n.
- A leading zero is not added to
mask. - A digit already in
maskis skipped. - At the end, we count 1 if at least one digit was placed.
Only states with limit and lead both false are cached, because they depend only on i and mask.
Complexity: O(log n * 210 * 10) time and O(log n * 210) space.
from functools import lru_cache
class Solution:
def countSpecialNumbers(self, n: int) -> int:
@lru_cache(None)
def dfs(i: int, mask: int, lead: bool, limit: bool) -> int:
if i >= len(s):
return int(lead ^ 1)
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
if mask >> j & 1:
continue
if lead and j == 0:
ans += dfs(i + 1, mask, True, limit and j == up)
else:
ans += dfs(i + 1, mask | 1 << j, False, limit and j == up)
return ans
s = str(n)
return dfs(0, 0, True, True)