KatInterview

Counting Sorted Sequences With Prescribed Digit Sums

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingprefix-sumstwo-pointers

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

  1. Every element is an integer between 0 and 5000, inclusive.
  2. The digit sum (the sum of the decimal digits) of seq[i] equals targets[i], for every index i.
  3. The sequence never decreases: seq[i] >= seq[i-1] for every i > 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 0 is 0.
  • If targets is empty, exactly one (empty) sequence exists, so return 1.
  • 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 is 0.

Constraints

  • targets may be empty. Its length can be large enough that an approach costing about n * 5000^2 operations 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.