Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 109 + 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 <= 10221 <= min_sum <= max_sum <= 400Problem summary: 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 109 + 7. Note that digit_sum(x) denotes the sum of the digits of x.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Dynamic Programming
"1" "12" 1 8
"1" "5" 1 5
count-numbers-with-non-decreasing-digits)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2719: Count of Integers
import java.math.BigInteger;
class Solution {
private final int mod = (int) 1e9 + 7;
private Integer[][] f;
private String num;
private int min;
private int max;
public int count(String num1, String num2, int min_sum, int max_sum) {
min = min_sum;
max = max_sum;
num = num2;
f = new Integer[23][220];
int a = dfs(0, 0, true);
num = new BigInteger(num1).subtract(BigInteger.ONE).toString();
f = new Integer[23][220];
int b = dfs(0, 0, true);
return (a - b + mod) % mod;
}
private int dfs(int pos, int s, boolean limit) {
if (pos >= num.length()) {
return s >= min && s <= max ? 1 : 0;
}
if (!limit && f[pos][s] != null) {
return f[pos][s];
}
int ans = 0;
int up = limit ? num.charAt(pos) - '0' : 9;
for (int i = 0; i <= up; ++i) {
ans = (ans + dfs(pos + 1, s + i, limit && i == up)) % mod;
}
if (!limit) {
f[pos][s] = ans;
}
return ans;
}
}
// Accepted solution for LeetCode #2719: Count of Integers
func count(num1 string, num2 string, min_sum int, max_sum int) int {
const mod = 1e9 + 7
f := [23][220]int{}
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
num := num2
var dfs func(int, int, bool) int
dfs = func(pos, s int, limit bool) int {
if pos >= len(num) {
if s >= min_sum && s <= max_sum {
return 1
}
return 0
}
if !limit && f[pos][s] != -1 {
return f[pos][s]
}
var ans int
up := 9
if limit {
up = int(num[pos] - '0')
}
for i := 0; i <= up; i++ {
ans = (ans + dfs(pos+1, s+i, limit && i == up)) % mod
}
if !limit {
f[pos][s] = ans
}
return ans
}
a := dfs(0, 0, true)
t := []byte(num1)
for i := len(t) - 1; i >= 0; i-- {
if t[i] != '0' {
t[i]--
break
}
t[i] = '9'
}
num = string(t)
f = [23][220]int{}
for i := range f {
for j := range f[i] {
f[i][j] = -1
}
}
b := dfs(0, 0, true)
return (a - b + mod) % mod
}
# Accepted solution for LeetCode #2719: Count of Integers
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
// Accepted solution for LeetCode #2719: Count of Integers
/**
* [2719] Count of Integers
*/
pub struct Solution {}
// submission codes start here
struct DigitDP {
num1: Vec<u32>,
num2: Vec<u32>,
min_sum: u32,
max_sum: u32,
dp_vec: Vec<Vec<i32>>,
}
impl DigitDP {
pub fn new(num1: Vec<u32>, num2: Vec<u32>, min_sum: u32, max_sum: u32) -> DigitDP {
let mut dp = Vec::with_capacity(num2.len());
for _ in 0..num2.len() {
let length = num2.len() * 9 + 1;
let mut array = Vec::with_capacity(length);
array.resize(length, -1);
dp.push(array)
}
DigitDP {
num1,
num2,
min_sum,
max_sum,
dp_vec: dp,
}
}
pub fn dp(&mut self, sum: u32, l_limit: bool, r_limit: bool, index: usize) -> i32 {
if index >= self.num2.len() {
return if sum >= self.min_sum && sum <= self.max_sum {
1
} else {
0
};
}
if !l_limit && !r_limit && self.dp_vec[index][sum as usize] != -1 {
return self.dp_vec[index][sum as usize];
}
let low = if l_limit { self.num1[index] } else { 0 };
let high = if r_limit { self.num2[index] } else { 9 };
let mut result = 0;
for i in low..=high {
result += DigitDP::dp(
self,
sum + i,
i == self.num1[index] && l_limit,
i == self.num2[index] && r_limit,
index + 1,
);
if result > 1000000007 {
result = result % 1000000007
}
}
if !l_limit && !r_limit {
self.dp_vec[index][sum as usize] = result;
}
result
}
}
impl Solution {
pub fn count(num1: String, num2: String, min_sum: i32, max_sum: i32) -> i32 {
let mut num1 = Solution::str_to_vec(num1);
let num2 = Solution::str_to_vec(num2);
// 将两个数组的长度对齐,在num1前面填0
for _ in 0..(num2.len() - num1.len()) {
num1.insert(0, 0);
}
let mut digit_dp = DigitDP::new(num1, num2, min_sum as u32, max_sum as u32);
digit_dp.dp(0, true, true, 0)
}
fn str_to_vec(num: String) -> Vec<u32> {
let mut num_vec = Vec::new();
for c in num.chars() {
match c.to_digit(10) {
None => {}
Some(i) => num_vec.push(i),
}
}
num_vec
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2719() {
assert_eq!(
Solution::count(String::from("1"), String::from("12"), 1, 8),
11
);
assert_eq!(
Solution::count(String::from("1"), String::from("5"), 1, 5),
5
);
}
}
// Accepted solution for LeetCode #2719: Count of Integers
function count(num1: string, num2: string, min_sum: number, max_sum: number): number {
const mod = 1e9 + 7;
const f: number[][] = Array.from({ length: 23 }, () => Array(220).fill(-1));
let num = num2;
const dfs = (pos: number, s: number, limit: boolean): number => {
if (pos >= num.length) {
return s >= min_sum && s <= max_sum ? 1 : 0;
}
if (!limit && f[pos][s] !== -1) {
return f[pos][s];
}
let ans = 0;
const up = limit ? +num[pos] : 9;
for (let i = 0; i <= up; i++) {
ans = (ans + dfs(pos + 1, s + i, limit && i === up)) % mod;
}
if (!limit) {
f[pos][s] = ans;
}
return ans;
};
const a = dfs(0, 0, true);
num = (BigInt(num1) - 1n).toString();
f.forEach(v => v.fill(-1));
const b = dfs(0, 0, true);
return (a - b + mod) % mod;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.