Algorithms · Visualized
DP: Digit DP (Count by Digit Sum)
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Counts how many integers in the range 0..N have a given digit sum by building the number digit by digit from the most significant end. Time: O(d·s·10) average, O(d·s·10) worst; space: O(d·s) memo table, where d is the digit count and s the target sum.
Big-O: The most-asked interview category — 35 classics here.
Digit DP (Count by Digit Sum)
Dynamic ProgrammingCounts how many integers in the range 0..N have a given digit sum by building the number digit by digit from the most significant end. The state is the position, the sum accumulated so far, and a "tight" flag recording whether the prefix still equals N’s prefix. When tight is false every digit 0–9 is allowed and the remaining count depends only on position and sum, so it is memoised; when tight is true only digits up to N’s current digit are allowed.
How Digit DP (Count by Digit Sum) Works
- Write N as a digit array.
- Define solve(pos, sum, tight): the number of valid completions from this position.
- If pos is past the last digit, return 1 when sum equals the target, else 0.
- Try every digit from 0 up to (tight ? N[pos] : 9).
- Recurse with the new sum and tight && digit === N[pos], memoising when not tight.
Digit DP (Count by Digit Sum) Worked Example
Input:
N = 20, target sum 2: numbers 2, 11 and 20 qualify. The tight branch follows 2 then 0, while the loose branch counts all one-digit and two-digit completions with the remaining sum.
| s=0 | s=1 | |
|---|---|---|
| pos0 (≤1) | ||
| pos1 (≤0) | ||
| pos2 (≤0) | ||
| end |
from functools import lru_cache
def count_sum(n, target):
digits = list(map(int, str(n)))
@lru_cache(None)
def f(pos, s, tight): # pos, sum so far, prefix==n?
if s > target: return 0
if pos == len(digits):
return 1 if s == target else 0
lim = digits[pos] if tight else 9
return sum(f(pos + 1, s + d, tight and d == lim)
for d in range(lim + 1))
return f(0, 0, True)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Digit DP (Count by Digit Sum) Time & Space Complexity
When to Use Digit DP (Count by Digit Sum)
- Counting integers with a digit property inside a range (sum, product, repeated digits).
- The standard technique for “numbers up to N” constraints in competitive programming.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.