Numbers With Repeated Digits Problem
Description
LeetCode Problem 1012.
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.
Example 1:
Input: n = 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: n = 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: n = 1000
Output: 262
Constraints:
1 <= n <= 10^9
Solution
Approach: Digit DP on the Complement
Counting numbers with a repeated digit is awkward; counting numbers whose digits are all distinct is easier. The answer is n minus that count.
To count the numbers in [1, n] with distinct digits, build them digit by digit from the left, using the digits of n as the limit. The state of count(i, mask, lead, limit) is:
i: the position we are filling.mask: the set of digits used so far, as 10 bits.lead: we have only placed leading zeros so far, so the number has not really started.limit: the digits so far are equal ton's prefix, so this digit can be at mostn's digiti(otherwise up to 9).
At position i, try each digit d allowed by the limit:
- If
leadandd = 0, it is another leading zero: it does not go intomask(otherwise numbers like105would look like they repeat the 0 of0105). - Otherwise
dmust not be inmaskyet; add it and continue withlead = false.
When all positions are filled, count 1, unless lead is still true: that is the number 0, which is not in the range.
Only the states with lead and limit both false repeat, so those are the ones we memoize, by (i, mask).
Complexity: O(D · 210 · 10) time and O(D · 210) space, where D ≤ 10 is the number of digits of n.
from functools import lru_cache
class Solution:
def numDupDigitsAtMostN(self, n: int) -> int:
s = str(n)
@lru_cache(None)
def count(i: int, mask: int, lead: bool, limit: bool) -> int:
"""Ways to fill digits i.. with no digit used twice.
mask: digits used so far; lead: only leading zeros so far; limit: prefix equals n's prefix."""
if i == len(s):
return 0 if lead else 1 # all leading zeros is the number 0, which is not counted
up = int(s[i]) if limit else 9
total = 0
for d in range(up + 1):
if lead and d == 0:
total += count(i + 1, mask, True, limit and d == up) # still a leading zero
elif not mask >> d & 1:
total += count(i + 1, mask | 1 << d, False, limit and d == up)
return total
# Numbers with a repeated digit = all numbers minus those with all digits distinct.
return n - count(0, 0, True, True)