#2719
Count of Integers
HardMathStringDynamic ProgrammingDynamic ProgrammingDigit DP
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * max_sum) |
| Space | O(1) | O(n * max_sum) |
💡
Intuition
Time O(n * max_sum)Space O(n * max_sum)
Instead of checking each integer, we can use a dynamic programming approach to count the number of integers with a digit sum within the specified range. This is more efficient as it avoids redundant calculations.
⚙️
Algorithm
5 steps- 1Step 1: Define a function f(n, l, r) to count integers from 1 to n with digit sums between l and r.
- 2Step 2: Use dynamic programming to build a table that keeps track of the number of ways to form digit sums.
- 3Step 3: Calculate f(num2, min_sum, max_sum) and f(num1 - 1, min_sum, max_sum).
- 4Step 4: The result is f(num2, min_sum, max_sum) - f(num1 - 1, min_sum, max_sum).
- 5Step 5: Return the result modulo 10^9 + 7.
solution.py15 lines
1# Full working Python code
2
3def count_digit_sum(n, min_sum, max_sum):
4 dp = [[0] * (max_sum + 1) for _ in range(len(n) + 1)]
5 dp[0][0] = 1
6 for i in range(1, len(n) + 1):
7 for j in range(10):
8 for k in range(max_sum + 1):
9 if k + j <= max_sum:
10 dp[i][k + j] = (dp[i][k + j] + dp[i - 1][k]) % (10**9 + 7)
11 return sum(dp[len(n)][min_sum:max_sum + 1]) % (10**9 + 7)
12
13
14def count_good_integers(num1, num2, min_sum, max_sum):
15 return (count_digit_sum(num2, min_sum, max_sum) - count_digit_sum(str(int(num1) - 1), min_sum, max_sum)) % (10**9 + 7)ℹ
Complexity note: The time complexity is O(n * max_sum) because we are filling a DP table of size (length of n) x (max_sum). This is efficient compared to the brute force approach.
- 1Using dynamic programming can significantly reduce time complexity.
- 2Understanding digit sums and their properties is key to solving this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.