Count Numbers With Unique Digits II Problem
#3032
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 3032.
Given two positive integers a and b, return the count of numbers having unique digits in the range [a, b] (inclusive).
Example 1:
Input: a = 1, b = 20
Output: 19
Explanation: All the numbers in the range [1, 20] have unique digits except 11. Hence, the answer is 19.
Example 2:
Input: a = 9, b = 19
Output: 10
Explanation: All the numbers in the range [9, 19] have unique digits except 11. Hence, the answer is 10.
Example 3:
Input: a = 80, b = 120
Output: 27
Explanation: There are 41 numbers in the range [80, 120], 27 of which have unique digits.
Constraints:
1 <= a <= b <= 1000
Solution
Approach: Bitmask + Digit DP
Let f(n) be how many numbers in [1, n] have all digits distinct. The answer is f(b) - f(a - 1).
To compute f(n), write n as a digit string and use a memoized search dfs(pos, mask, limit):
posis the digit position being filled, from the most significant one.maskis the set of digits used so far, stored as a 10-bit number. Leading zeros do not count as used, somaskstays0until the first nonzero digit.limittells whether the digits so far equal the prefix ofn, in which case the current digit can be at mostn[pos].
At each position we try every allowed digit that is not already in mask. Past the last position we return 1 if at least one nonzero digit was placed, else 0. Results are cached only when limit is false. The answer for n is dfs(0, 0, true).
Complexity: time O(10 * m * 2^10), space O(m * 2^10), where m is the number of digits of b.
from functools import lru_cache
class Solution:
def numberCount(self, a: int, b: int) -> int:
@lru_cache(None)
def dfs(pos: int, mask: int, limit: bool) -> int:
if pos >= len(num):
return 1 if mask else 0
up = int(num[pos]) if limit else 9
ans = 0
for i in range(up + 1):
if mask >> i & 1:
continue
nxt = 0 if mask == 0 and i == 0 else mask | 1 << i
ans += dfs(pos + 1, nxt, limit and i == up)
return ans
num = str(a - 1)
x = dfs(0, 0, True)
dfs.cache_clear()
num = str(b)
y = dfs(0, 0, True)
return y - x