Digit-Sum Frequency Peaks
Dynamic ProgrammingModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that we don't need to store which specific integers have which digit sum—only how many integers map to each possible digit sum. Once we have a frequency table, we find the maximum frequency and count how many sums achieve it.
Solution 1: Direct Enumeration
For moderate values of n (up to around 10^6), we can iterate through all integers from 1 to n, compute each digit sum, and maintain a frequency counter.
from collections import Counter
def digitSumPeaks(n: int) -> int:
freq = Counter()
for i in range(1, n + 1):
digit_sum = sum(int(d) for d in str(i))
freq[digit_sum] += 1
max_freq = max(freq.values())
return sum(1 for count in freq.values() if count == max_freq)
Complexity:
- Time: O(n log n) — we process n numbers, each requiring O(log n) time to extract and sum digits
- Space: O(log n) — the frequency table has at most 9 × (number of digits) entries
This approach is straightforward and works well for typical problem constraints.
Solution 2: Digit Dynamic Programming
For very large n (up to 10^18), we need a sublinear approach. Digit DP allows us to count integers with each digit sum without enumerating them.
Key Idea: Build a table dp[k][s] representing the count of k-digit strings (with leading zeros allowed) that have digit sum s. Then walk through the digits of n from left to right, accumulating counts for all numbers ≤ n.
DP Recurrence:
dp[k][s] = sum over all digits d in 0..9 of dp[k-1][s-d]
Base case: dp[0][0] = 1 (empty string has sum 0)
Counting numbers ≤ n: For each position i in n with digit c:
- Try all smaller digits x < c at this position
- The remaining positions are completely free, so add
dp[remaining][target_sum]to our counts - Then commit to digit c and move to the next position
- Finally, add n itself
def digitSumPeaks(n: int) -> int:
digits = [int(d) for d in str(n)]
num_digits = len(digits)
max_sum = 9 * num_digits
# Build DP table
dp = [[0] * (max_sum + 1) for _ in range(num_digits + 1)]
dp[0][0] = 1
for k in range(1, num_digits + 1):
for s in range(9 * k + 1):
for digit in range(10):
if s >= digit:
dp[k][s] += dp[k-1][s - digit]
# Count frequencies for [0, n]
freq = [0] * (max_sum + 1)
current_sum = 0
for i, c in enumerate(digits):
remaining = num_digits - i - 1
# Try all smaller digits at position i
for x in range(c):
prefix_sum = current_sum + x
# Add counts for all ways to fill remaining positions
for tail_sum in range(9 * remaining + 1):
freq[prefix_sum + tail_sum] += dp[remaining][tail_sum]
current_sum += c
# Add n itself
freq[current_sum] += 1
# Remove 0 (range starts at 1, not 0)
freq[0] -= 1
# Find maximum frequency among valid sums (≥ 1)
max_freq = max(freq[1:])
return sum(1 for s in range(1, max_sum + 1) if freq[s] == max_freq)
Complexity:
- Time: O(log² n) — the DP table has O(log n) rows and O(log n) columns, each cell computed from 10 transitions
- Space: O(log² n) — storing the DP table
For n = 10^18, this means roughly 18 digits and about 30,000 operations—easily feasible.
Edge Cases
- n = 1: Only one number with digit sum 1. Answer: 1
- n = 9: Each digit sum 1 through 9 appears exactly once. All nine sums tie. Answer: 9
- n = 100: Numbers 1-100. Sum 1 appears in {1, 10, 100}, creating a peak
- Powers of ten: Handle trailing zeros carefully in the digit walk
Common Mistakes
- Including zero: The range starts at 1, not 0. Subtract the count for sum 0 from the DP result
- Overflow: For languages without arbitrary precision, use 64-bit integers—frequencies can approach n/9
- Off-by-one in DP bounds: Ensure the DP table accommodates the maximum possible sum (9 × number of digits)
- Forgetting to add n itself: The digit walk counts numbers strictly less than n, so add n as a final step
What Strong Candidates Demonstrate
- Immediate recognition that only frequencies matter, never materializing the full list
- Clear complexity analysis for the brute-force approach
- Knowledge of digit DP as a technique for handling large numeric ranges
- Proper handling of the zero exclusion
- Testing against a brute-force implementation on small inputs to validate correctness