KatInterview

Digit-Sum Frequency Peaks

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdigit-dpcombinatoricsmath

Last updated

Count how many digit-sum values tie for the most occurrences among integers 1 through n.

You are working with a range of consecutive integers from 1 to n. For each integer, compute the sum of its digits. Your task is to determine how many distinct digit-sum values appear most frequently across this range.

For example, if n = 12:

  • 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
  • Frequencies: sum 1 appears twice, sum 2 appears twice, sum 3 appears twice, all others appear once
  • The maximum frequency is 2, achieved by three distinct sums (1, 2, and 3)
  • Answer: 3

Write a function that takes n as input and returns the count of digit-sum values that achieve the maximum frequency. Analyze the time and space complexity of your solution, and discuss how you would handle very large values of n (up to 10^18).

Hints

Hint 1

You only need the frequency distribution of digit sums, not the individual numbers themselves.

Hint 2

For small n, iterate through all integers and count. For large n, consider digit dynamic programming to avoid explicit enumeration.

Hint 3

The digit DP state can track position in the number and the running sum of digits chosen so far.