A village fair prints raffle tickets numbered lo to hi in plain decimal (no leading zeros). The stamp for digit d is nearly worn out: it can print d at most k times on one ticket.
Implement count_tickets(lo: int, hi: int, d: int, k: int) -> int: how many x in lo..hi contain the digit d at most k times?
count_tickets(1, 30, 2, 0) # 18 1..30 minus {2, 12, 20, 21, ..., 29}
count_tickets(95, 105, 0, 0) # 5 95..99; 100..105 all contain a 0
count_tickets(0, 0, 0, 0) # 0 the ticket "0" uses the digit 0 once
count_tickets(1000, 1000, 0, 2) # 0 "1000" has three zeros
0 <= lo <= hi <= 10**18, 0 <= d <= 9, 0 <= k <= 19. Careful with d = 0: 7 has no zeros (leading zeros aren't printed), but 0 itself is printed as one 0.
⭐ Bonus: looping over the range passes for small ranges; a speed test with ranges up to 10**18 numbers earns a star with a digit DP.
Show hint
answer f(hi) - f(lo - 1), where f(n) counts 0..n. Build numbers from the left with memoized state (position, tight, started, uses of d); a 0 only counts toward d = 0 once the number has started.