Problem Description
Given three integers start, finish, and limit, and a 0-indexed string s representing a positive integer, count how many powerful integers x in the interval [start, finish] exist such that:
- x ends with s (s is a suffix of x).
- Every digit in x is at most limit. Note that s has no leading zeros and its digits are all at most limit.
Internally, any such x can be written as: x = k * 10^(|s|) + offset , where offset = integer value of s. The problem then reduces to finding all values k for which: start ≤ k * 10^(|s|) + offset ≤ finish and the digits of both k (when written normally) and s are ≤ limit.
Key Insights
- Express every candidate integer x in the form k * 10^(|s|) + offset; this isolates the suffix.
- Compute the valid k-range from the inequality: start ≤ k * base + offset ≤ finish.
- The condition “each digit is at most limit” must hold for both s (given) and the prefix k; therefore, count only those k (within the computed range) whose decimal digits are all among 0, 1, …, limit.
- For limit = 9, since all digits are valid, the problem reduces to counting the number of integers in the k-range.
- For other values of limit, use a digit DP (dynamic programming) approach to count the numbers in a range satisfying the digit constraint.
Space and Time Complexity
Time Complexity: O(D * 2 * 2) per DP call where D is the maximum number of digits in k_max (at most 15). Counting valid k in the range uses two DP calls. Space Complexity: O(D * 2 * 2) for memoization in the DP. Note: Since the maximum number of digits is small, the DP approach is efficient.
Solution
We first determine: base = 10^(|s|) offset = integer value of s Then, we solve for k in the inequality: start ≤ k * base + offset ≤ finish ⇒ k ∈ [ceil((start - offset) / base), floor((finish - offset) / base)] Let k_low and k_high be the bounds (adjusting k_low to at least 0). We then need to count, among all k in [k_low, k_high], those whose decimal representation has each digit ≤ limit.
When limit equals 9, no extra filtering is needed. For other cases, we use a digit DP counting function that given an integer N returns how many numbers in [0, N] are “digit-limited” (each digit is in [0, limit]). Using this function, the answer is: dp(k_high) - dp(k_low - 1) This approach uses a DP that iterates over the digits of N and at each step considers digits allowed by the limit, taking into account whether we are still “tight” with N and whether we have started the number (to handle leading zeros properly).