Count Sorted Sequences Matching Per-Position Digit Sums
Dynamic ProgrammingAuto-graded · 23 test casesLast updated
Tests dynamic programming over value buckets with a two-pointer prefix-sum transition to count sorted integer sequences under a digit-sum constraint.
Problem
You are given an integer array digit_sums of length n. Count the number of distinct integer arrays seq of the same length that satisfy all of the following:
- Bounded values: every element satisfies
1 <= seq[i] <= 5000. - Digit sum match: for every index
i, the sum of the base-10 digits ofseq[i]equalsdigit_sums[i]. - Non-decreasing order:
seq[i] <= seq[i + 1]for every adjacent pair.
Return the count modulo 1 000 000 007. Two sequences are considered distinct if they differ at any position. Adjacent equal values are permitted.
Constraints
1 <= n <= 50001 <= digit_sums[i] <= 31for every indexi
Examples
Example 1
Input: count_non_decreasing_arrays([1])
Output: 4
Example 2
Input: count_non_decreasing_arrays([1, 1])
Output: 10
Hints
Hint 1
For each required digit sum, precompute every integer in [1, 5000] that achieves it. These candidate lists come out sorted if you iterate values in order — that sorted property is useful later.
Hint 2
Model this as a layer-by-layer DP: dp[j] = number of valid sequences ending at position i with value candidates[j]. To move to the next layer, you need the sum of dp[j] over all previous candidates that are <= the current candidate.
Hint 3
Both the previous and next candidate lists are sorted. Use a two-pointer running prefix sum: walk through the next candidates in order and advance a pointer through the previous candidates while they are <= the current value. This reduces the transition from O(|prev| * |next|) to O(|prev| + |next|).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Bucket values by digit sum
Every legal value for position i must lie in [1, 5000] and have a digit sum equal to digit_sums[i]. Precompute this once: iterate all integers from 1 to 5000, compute each one's digit sum, and place it into the matching bucket. Because we iterate in ascending order, each bucket comes out sorted for free.
Step 2 — Layer-by-layer DP
Define dp[j] as the number of valid sequences ending at the current position with the value candidates[j], where candidates is the bucket for the current digit sum.
Base case (position 0): every candidate starts exactly one sequence, so dp[j] = 1 for all j.
Transition (position i → i + 1): for a next candidate v, the previous value can be anything in the previous bucket that is <= v (the non-decreasing condition, with equality allowed). So:
next_dp[v] = sum of dp[u] for all previous candidates u <= v
Step 3 — Two-pointer prefix sum
A naive transition is O(|prev| × |next|). Because both lists are sorted, we can do it in O(|prev| + |next|) with two pointers:
- Walk
next_candidatesin increasing order. - Maintain a running sum and a pointer into
prev_candidates. - Advance the pointer (and add to the running sum) while
prev_candidates[ptr] <= v. - The running sum at that point is exactly
next_dp[v].
The pointer never moves backward, so the whole transition is linear.
Why it is correct
- Every legal value appears in exactly one bucket, so no valid sequence is missed or double-counted.
- The DP invariant holds by induction: after processing position
i,dp[j]counts all valid prefixes of lengthi + 1ending atcandidates[j]. - The
<=in the pointer condition correctly allows equal adjacent values. - If any digit sum has an empty bucket, no valid sequence exists and we return 0 immediately.
Edge cases
n = 1: the answer is just the size of the matching bucket. Digit sum 1 gives{1, 10, 100, 1000}, so 4.- Infeasible ordering: e.g.,
digit_sums = [28, 1]— all digit-sum-28 values exceed every digit-sum-1 value, so everynext_dpentry is 0 and the answer is 0. - Digit sum 31: only
4999qualifies, so any subsequent position must also admit a value>= 4999. The prefix logic handles this without special cases.
Complexity
- Precomputation: O(5000) — a small constant.
- Per transition: O(|prev bucket| + |next bucket|), both at most a few hundred.
- Total time: O(n × G) where G is the largest bucket size. With n = 5000 and G << 5000 in practice, this is well within limits.
- Space: O(5000) for buckets plus O(G) for two rolling DP arrays — no full n × 5000 table needed.
Reference solution
from typing import List
MOD = 1_000_000_007
def count_non_decreasing_arrays(digit_sums: List[int]) -> int:
if not digit_sums:
return 0
# Precompute candidate lists: buckets[s] holds every integer in [1, 5000]
# whose base-10 digit sum equals s, in ascending order.
buckets = [[] for _ in range(32)]
for value in range(1, 5001):
x, s = value, 0
while x:
s += x % 10
x //= 10
buckets[s].append(value)
first = digit_sums[0]
if first < 0 or first >= len(buckets) or not buckets[first]:
return 0
# Base layer: each candidate at position 0 starts exactly one sequence.
candidates = buckets[first]
dp = [1] * len(candidates)
for target in digit_sums[1:]:
if target < 0 or target >= len(buckets) or not buckets[target]:
return 0
next_candidates = buckets[target]
next_dp = []
prev_ptr = 0
running = 0
# Two-pointer merge: for each next candidate v, accumulate dp values
# of all previous candidates <= v (non-decreasing allows equality).
for v in next_candidates:
while prev_ptr < len(candidates) and candidates[prev_ptr] <= v:
running = (running + dp[prev_ptr]) % MOD
prev_ptr += 1
next_dp.append(running)
candidates = next_candidates
dp = next_dp
return sum(dp) % MOD