Count of Integers Problem
Description
LeetCode Problem 2719.
You are given two numeric strings num1 and num2 and two integers max_sum and min_sum. We denote an integer x to be good if:
num1 <= x <= num2min_sum <= digit_sum(x) <= max_sum.
Return the number of good integers. Since the answer may be large, return it modulo 10^9 + 7.
Note that digit_sum(x) denotes the sum of the digits of x.
Example 1:
Input: num1 = "1", num2 = "12", min_sum = 1, max_sum = 8
Output: 11
Explanation: There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11.
Example 2:
Input: num1 = "1", num2 = "5", min_sum = 1, max_sum = 5
Output: 5
Explanation: The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.
Constraints:
1 <= num1 <= num2 <= 10^221 <= min_sum <= max_sum <= 400
Solution
Approach: Digit DP
We need the number of integers in [num1, num2] whose digit sum lies in [min_sum, max_sum]. Count the good integers in [0, num2] and subtract the count for [0, num1 - 1].
To count the good integers up to a bound num, use a memoized search dfs(pos, s, limit): we are about to choose the digit at position pos (from the most significant digit), the digits so far sum to s, and limit says whether the digits so far equal the prefix of num (so the next digit may not exceed num[pos]).
- Try every digit
ifrom0toup, whereup = num[pos]iflimitis set and9otherwise, and recurse intodfs(pos + 1, s + i, limit and i == up). - When
posreaches the end ofnum, return1ifmin_sum <= s <= max_sum, else0. - Only the states with
limitunset are cached, since they do not depend on the bound.
Take the difference modulo 10^9 + 7. Because num1 has up to 22 digits, num1 - 1 is computed on the string with big integers.
Complexity: O(10 · n · S) time and O(n · S) space, where n ≤ 22 is the number of digits and S is the largest possible digit sum (at most 9n).
from functools import lru_cache
class Solution:
def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int:
@lru_cache(None)
def dfs(pos: int, s: int, limit: bool) -> int:
if pos >= len(num):
return int(min_sum <= s <= max_sum)
up = int(num[pos]) if limit else 9
return (
sum(dfs(pos + 1, s + i, limit and i == up) for i in range(up + 1)) % mod
)
mod = 10**9 + 7
num = num2
a = dfs(0, 0, True)
dfs.cache_clear()
num = str(int(num1) - 1)
b = dfs(0, 0, True)
return (a - b) % mod