Count Distinct Integers After Removing Zeros Problem
Description
LeetCode Problem 3747.
You are given a positive integer n.
For every integer x from 1 to n, we write down the integer obtained by removing all zeros from the decimal representation of x.
Return an integer denoting the number of distinct integers written down.
Example 1:
Input: n = 10
Output: 9
Explanation:
The integers we wrote down are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1. There are 9 distinct integers (1, 2, 3, 4, 5, 6, 7, 8, 9).
Example 2:
Input: n = 3
Output: 3
Explanation:
The integers we wrote down are 1, 2, 3. There are 3 distinct integers (1, 2, 3).
Constraints:
1 <= n <= 10^15
Solution
Approach: Digit DP
Removing the zeros from x gives a number with no zero digits, and every zero-free number y <= n is produced by x = y itself. Different zero-free numbers stay different, so the answer is the count of integers in [1, n] that contain no digit 0.
We count them with a digit DP over the decimal digits of n. The function dfs(i, zero, lead, limit) handles digit i and remembers three things: zero (a zero digit appeared after the number started), lead (we are still in leading zeros, so the number has not started), and limit (the prefix equals the prefix of n, so the digit is capped by n's digit). At the end, a number counts when it has started and has no inner zero. Results for limit = false are memoized by (i, zero, lead).
Complexity: time O(10 * log n), space O(log n), where log n is the number of digits.
from functools import lru_cache
class Solution:
def countDistinct(self, n: int) -> int:
@lru_cache(None)
def dfs(i: int, zero: bool, lead: bool, lim: bool) -> int:
if i >= len(s):
return 1 if (not zero and not lead) else 0
up = int(s[i]) if lim else 9
ans = 0
for j in range(up + 1):
nxt_zero = zero or (j == 0 and not lead)
nxt_lead = lead and j == 0
nxt_lim = lim and j == up
ans += dfs(i + 1, nxt_zero, nxt_lead, nxt_lim)
return ans
s = str(n)
return dfs(0, False, True, True)