KatInterview

Count Sorted Sequences Matching Per-Position Digit Sums

Dynamic ProgrammingAuto-graded · 23 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingarraysmath-bits

Last 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:

  1. Bounded values: every element satisfies 1 <= seq[i] <= 5000.
  2. Digit sum match: for every index i, the sum of the base-10 digits of seq[i] equals digit_sums[i].
  3. 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 <= 5000
  • 1 <= digit_sums[i] <= 31 for every index i

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|).