Count of Integers - 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

Return the number of good integers. Since the answer may be large, return it modulo 10^9 + 7.

Note: digit_sum(x) denotes the sum of the digits of x.

Input & Output

Example 1 — Basic Range
$ Input: num1 = "1", num2 = "12", min_sum = 1, max_sum = 8
Output: 12
💡 Note: Numbers 1-12 have digit sums: 1(1), 2(2), 3(3), 4(4), 5(5), 6(6), 7(7), 8(8), 9(9), 10(1), 11(2), 12(3). All have digit sum ≤ 8 and ≥ 1, so count = 12.
Example 2 — Narrow Sum Range
$ Input: num1 = "1", num2 = "5", min_sum = 1, max_sum = 3
Output: 3
💡 Note: Numbers 1,2,3 have digit sums 1,2,3 respectively (all valid). Numbers 4,5 have digit sums 4,5 (both > 3, invalid). Count = 3.
Example 3 — Single Number
$ Input: num1 = "15", num2 = "15", min_sum = 5, max_sum = 8
Output: 1
💡 Note: Only number 15 in range. Digit sum = 1+5 = 6, which satisfies 5 ≤ 6 ≤ 8. Count = 1.

Constraints

  • 1 ≤ num1 ≤ num2 < 1022
  • 1 ≤ min_sum ≤ max_sum ≤ 400

Visualization

Tap to expand
Count of Integers - DP Approach INPUT Range: num1 to num2 1 2 3 ... 11 12 Parameters num1 = "1" num2 = "12" min_sum = 1 max_sum = 8 Digit Sum Constraint 1 <= digit_sum(x) <= 8 e.g., digit_sum(12)=1+2=3 ALGORITHM STEPS 1 Define DP State dp[pos][sum][tight] 2 Count f(num2) Count nums <= num2 with valid digit sum 3 Count f(num1-1) Count nums < num1 with valid digit sum 4 Subtract Result = f(num2) - f(num1-1) DP Transitions For each digit d (0-9): new_sum = sum + d if new_sum <= max_sum: recurse FINAL RESULT Valid Numbers (digit_sum 1-8) 1 2 3 4 5 6 7 8 10 11 12 Excluded: 9 (sum=9 > 8) OUTPUT 11 Calculation: f(12) - f(0) = 11 - 0 OK - 11 good integers Key Insight: Use Digit DP with states: position, current digit sum, and tight constraint. Count valid numbers up to num2, subtract count up to (num1-1). Apply modulo 10^9+7. TutorialsPoint - Count of Integers | Digit DP Approach
Asked in
Google 15 Meta 12 Amazon 8
12.8K Views
Medium Frequency
~35 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen