KatInterview

Most Populous Digit-Sum Group in a Number Range

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdigit-dpcountingrange-queries

Last 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 0 has digit sum 0.
  • If lo == hi, the range holds one number, so the answer is 1.
  • The function returns a single integer, the size of the largest group, not the digit sum itself.

Constraints

  • 0 <= lo <= hi <= 10^18
  • lo and hi are integers.
  • Your solution should finish quickly even when hi - lo is close to 10^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.