Problem Description
Given a single-digit integer d and two integers low and high, count the number of times that d occurs as a digit in every integer in the inclusive range [low, high].
Key Insights
- A brute-force iteration over the range [low, high] is too slow given the constraint high ≤ 2×10^8.
- We can use Digit Dynamic Programming (DP) to count occurrences of d in numbers up to a given limit.
- Calculate the count for the interval [0, high] and subtract the count for [0, low-1] to get the final answer.
- Care must be taken when d is 0, as leading zeroes should be handled correctly (they are not considered once the number starts).
Space and Time Complexity
Time Complexity: O(log(n) * (constant factor)) per DP call, where n is the high value. Space Complexity: O(log(n)) due to recursion depth and memoization storage.
Solution
We solve this problem using Digit DP. The approach is to build the count for every number from 0 up to n using recursion with memoization. At each digit position, we decide the current digit from 0 to a limit (which is the current digit of n if we are bounded by n’s prefix). The DP state considers:
- The current position in the digit string.
- Whether the prefix so far is "tight" (exactly matching the prefix of n).
- Whether we have begun placing non-zero digits (to avoid counting leading zeros).
The DP returns a tuple containing:
- The total number of times d occurs from the current state.
- The total number of numbers possible from the current state.
After computing the count for 0 to high and for 0 to low-1, subtracting the two gives the desired result for the range [low, high].