Most Populous Digit-Sum Group in a Number Range
Dynamic ProgrammingAuto-graded · 23 test casesLast updated
Count integers in a huge range grouped by digit sum and return the largest group size, which needs a digit DP with prefix-count subtraction rather than enumeration.
Given two non-negative integers lo and hi, consider every integer x with lo <= x <= hi (both ends included). Group these integers by the sum of their decimal digits, so that two numbers land in the same group exactly when their digit sums are equal. For example, the digit sum of 407 is 4 + 0 + 7 = 11.
Return the number of integers in the largest group. If several groups tie for the largest size, return that shared size.
The range can be very wide, so looping over every integer in it may be too slow. Aim for a solution whose running time depends on the number of digits of hi, not on hi - lo.
Details
- The number
0has digit sum0. - If
lo == hi, the range holds one number, so the answer is1. - The function returns a single integer, the size of the largest group, not the digit sum itself.
Constraints
0 <= lo <= hi <= 10^18loandhiare integers.- Your solution should finish quickly even when
hi - lois close to10^18.
Examples
Example 1
Input: most_common_digit_sum_count(1, 20)
Output: 3
Example 2
Input: most_common_digit_sum_count(10, 99)
Output: 9
Example 3
Input: most_common_digit_sum_count(0, 0)
Output: 1
Example 4
Input: most_common_digit_sum_count(98, 102)
Output: 1
Hints
Hint 1
Counting the numbers in [lo, hi] with a given digit sum equals counting those in [0, hi] minus those in [0, lo - 1]. Focus on how to count over a prefix range [0, n].
Hint 2
To count numbers up to n by digit sum, walk through n's digits from the most significant one. Track the single 'tight' prefix that still matches n, plus a table of how many prefixes are already strictly smaller than n, indexed by digit sum.
Hint 3
Once a prefix is strictly smaller than n's prefix, every remaining digit can be anything from 0 to 9, so its table entry spreads to 10 successor sums. Leading zeros do not change the digit sum, so you do not need a 'number started' flag. Compute the whole table for hi and for lo - 1, subtract entry by entry, and take the maximum.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking every number in the range costs about (hi - lo) * digits, which is far too slow when the range is huge. Instead, count the numbers per digit sum without listing them.
- Define
tally(n)[s]as the number of integers in[0, n]whose digit sum iss. The count for sumsinside[lo, hi]is thentally(hi)[s] - tally(lo - 1)[s]. The answer is the maximum of this difference over alls. - Build
tally(n)with a digit DP. Writenwith its digits from most significant to least significant and keep two things:free[s]: the number of prefixes that are already strictly smaller than the matching prefix ofnand have digit sums.tight: the digit sum of the one prefix that still equalsn's prefix.
- For each digit
limitofn:- Every prefix in
freecan be extended by any digit0..9, moving from sumstos + d. - The tight prefix can drop into
freeby taking any digitd < limit, giving sumtight + d. - The tight prefix stays tight by taking
limit, sotight += limit.
- Every prefix in
- After the last digit, add
1at indextightfornitself.
Why it is correct
Pad every x in [0, n] with leading zeros to the length of n. Then either x = n, or there is exactly one first position where x's digit is smaller than n's while all earlier digits agree. The DP creates each such x exactly once: it leaves the tight path at that position and is free afterwards. Nothing is missed or double-counted. Leading zeros do not change a digit sum, so shorter numbers (including 0) are counted correctly without a "started" flag. Subtracting the two tallies gives exact counts for [lo, hi]. Because only the maximum size is requested, ties need no special handling. When lo = 0, tally(-1) is empty and is treated as all zeros.
Complexity
Let D be the number of digits of hi (at most 19). The free array has O(9D) entries, each spreads to 10 successors, and this repeats for D digits, so the time is O(D^2) with a small constant. The space is O(D). Neither depends on hi - lo.
Reference solution
from itertools import zip_longest
def most_common_digit_sum_count(lo: int, hi: int) -> int:
def tally(n: int):
# tally(n)[s] = how many x in [0, n] have digit sum s
if n < 0:
return []
digits = [int(c) for c in str(n)]
size = 9 * len(digits) + 1
free = [0] * size # prefixes already strictly below n's prefix
tight = 0 # digit sum of the prefix equal to n's prefix
for limit in digits:
nxt = [0] * size
for s, c in enumerate(free):
if c:
for d in range(10):
nxt[s + d] += c
for d in range(limit):
nxt[tight + d] += 1
free = nxt
tight += limit
free[tight] += 1 # n itself
return free
upper = tally(hi)
lower = tally(lo - 1)
best = 0
for u, l in zip_longest(upper, lower, fillvalue=0):
if u - l > best:
best = u - l
return best