Counting Sorted Sequences With Prescribed Digit Sums
Dynamic ProgrammingAuto-graded · 25 test casesLast updated
Count non-decreasing sequences of integers in [0, 5000] whose i-th element has a given digit sum, using DP over candidate values with prefix sums, modulo 1,000,000,007.
You are given a list targets of integers. You must build a sequence seq with the same length as targets, and you want to know how many different sequences are possible.
A sequence is valid when all of these hold:
- Every element is an integer between
0and5000, inclusive. - The digit sum (the sum of the decimal digits) of
seq[i]equalstargets[i], for every indexi. - The sequence never decreases:
seq[i] >= seq[i-1]for everyi > 0. Equal neighbours are allowed.
Two sequences are different if they differ at one or more positions.
Return the number of valid sequences modulo 1_000_000_007.
Conventions
- The digit sum of
0is0. - If
targetsis empty, exactly one (empty) sequence exists, so return1. - If some target cannot be achieved by any integer in
[0, 5000](for example a negative target or a very large one), no valid sequence exists and the answer is0.
Constraints
targetsmay be empty. Its length can be large enough that an approach costing aboutn * 5000^2operations is too slow.- Each
targets[i]is an integer and may be negative or larger than any achievable digit sum. - Each chosen value must lie in
[0, 5000]. - Return the answer modulo
1_000_000_007.
Examples
Example 1
Input: count_digit_sum_sequences([1])
Output: 4
Example 2
Input: count_digit_sum_sequences([0])
Output: 1
Example 3
Input: count_digit_sum_sequences([1, 1])
Output: 10
Example 4
Input: count_digit_sum_sequences([1, 0])
Output: 0
Hints
Hint 1
Each position only allows the values in [0, 5000] with one specific digit sum. Group all 5001 values by digit sum once, in increasing order. Every group is small.
Hint 2
Let the DP state be the value chosen at the current position. The number of ways to end at value v is the sum of the ways at the previous position over all previous candidates that are <= v.
Hint 3
Both candidate lists are sorted, so that sum is a running prefix total. Sweep a pointer through the previous list while walking the current list, and you avoid any nested loop over candidates. Do not forget the modulus and the early return of 0 when a group is empty.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Position i can only take values in [0, 5000] whose digit sum equals targets[i]. We bucket all 5001 values by digit sum once. Because we insert them in increasing order, every bucket is already sorted. The largest digit sum in range is 31 (for 4999), so a target outside the achievable sums has an empty bucket, and the answer is 0.
We then run a DP over positions. For position i and the k-th candidate c in its bucket, dp[k] is the number of valid prefixes that end with c.
- Base case: every candidate at position 0 has
dp = 1. - Transition:
dp_i[k]is the sum ofdp_{i-1}[j]over all previous candidatespwithp <= c.
Since both candidate lists are sorted, the set of qualifying previous candidates is a prefix of the previous list, and that prefix only grows as c grows. So we sweep one pointer through the previous list while walking the current list, maintaining a running total modulo 10^9 + 7. The answer is the sum of the final DP row, modulo 10^9 + 7.
Why it is correct
- The only constraint linking positions is
seq[i] >= seq[i-1], so whether a prefix can be extended depends only on its last value. Indexing the DP by the last value loses no information. - A prefix ending in
pcan be extended withcexactly whenp <= c, so the transition counts each extension exactly once. The<=also covers equal neighbours. - Distinct paths through (position, value) pairs yield sequences that differ at some index, so nothing is double-counted.
- Infeasible targets give an empty bucket, which we return as
0immediately. An emptytargetslist gives1.
Complexity
Let B be the size of the largest bucket (a few hundred at most). Precomputation is about O(5000 * 4). Each step of the DP costs O(|prev| + |cur|), so the total is O(n * B) time, which is at most O(n * 5000). Space is O(5000) for the buckets plus O(B) for the two DP rows.
Reference solution
from typing import List
MOD = 1_000_000_007
MAX_VALUE = 5000
def _digit_sum(x: int) -> int:
total = 0
while x:
total += x % 10
x //= 10
return total
def count_digit_sum_sequences(targets: List[int]) -> int:
if not targets:
return 1
# Group every value in [0, MAX_VALUE] by digit sum; groups are ascending.
groups = {}
for v in range(MAX_VALUE + 1):
groups.setdefault(_digit_sum(v), []).append(v)
prev_vals = groups.get(targets[0], [])
if not prev_vals:
return 0
prev_dp = [1] * len(prev_vals)
for t in targets[1:]:
cur_vals = groups.get(t, [])
if not cur_vals:
return 0
cur_dp = []
j = 0
running = 0
for v in cur_vals:
while j < len(prev_vals) and prev_vals[j] <= v:
running = (running + prev_dp[j]) % MOD
j += 1
cur_dp.append(running)
prev_vals, prev_dp = cur_vals, cur_dp
return sum(prev_dp) % MOD