Learn / Dynamic programming

Digit DP

Digit DP counts numbers up to N with some property by building them digit by digit. The state is (position, whether the prefix so far is still equal to N's prefix, and whatever the property needs, such as a digit sum). Digits after the prefix falls below N are free. The sheets this guide follows have no digit-DP problems, so this lesson only explains the idea.

How to recognise it

  • Count numbers in a range [L, R] with a digit property.
  • R is huge (up to 10^18), so checking each number is impossible.
  • The property depends only on the digits, such as sums or forbidden digits.

Building a number

count(pos, tight, sum):
    if pos == len(N): return 1 if sum is good else 0
    limit = N[pos] if tight else 9
    total = 0
    for d in 0..limit: total += count(pos + 1, tight and d == limit, sum + d)
    return total

Memoise on (pos, tight, sum). Leading zeros sometimes need their own flag.

Common mistakes

  • Forgetting the tight flag, which counts numbers above N.
  • Mishandling leading zeros when they affect the property.

Problems

No problems listed for this pattern yet.

Check yourself

Why track whether the prefix is still 'tight'?

How do you count in a range [L, R]?

How many states for numbers up to 10^18 and digit sums up to 162?