Count of Integers — LeetCode 2719 Python Solution

HardMathStringDynamic Programming
Problem
#2719
Reading time
3 min

The problem

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 <= num2 min_sum <= digit_sum(x) <= max_sum.

Example

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.

Python solution

Python
class Solution:
    def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int:
        @cache
        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

Complexity

MeasureComplexity
TimeO(10 \times n \times max\_sum)
SpaceO(n \times max\_sum) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2719. Count of Integers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2719. Count of Integers?
LeetCode 2719. Count of Integers is rated Hard on LeetCode.
What is the time complexity of LeetCode 2719. Count of Integers?
The Python solution on this page runs in O(10 \times n \times max\_sum).
What is the space complexity of LeetCode 2719. Count of Integers?
The Python solution on this page uses O(n \times max\_sum) auxiliary space.
What topics does LeetCode 2719. Count of Integers cover?
LeetCode 2719. Count of Integers is tagged Math, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview