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 Programming

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

  1. Write N as a digit array.
  2. Define solve(pos, sum, tight): the number of valid completions from this position.
  3. If pos is past the last digit, return 1 when sum equals the target, else 0.
  4. Try every digit from 0 up to (tight ? N[pos] : 9).
  5. 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.

DP: Digit DP (Count by Digit Sum)O(digits·S·10)
Count numbers ≤ N with digit sum S via pos/sum/tight memo.
s=0s=1
pos0 (≤1)
pos1 (≤0)
pos2 (≤0)
end
1
0
0
012
target1
Step 1 / 5
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Digit DP: count numbers in [0, 100] whose digits sum to 1 — position by position with tight/loose memo.
Python · Dynamic Programming Algorithms in Code
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

BestO(d·s·10)
AverageO(d·s·10)
WorstO(d·s·10)
SpaceO(d·s) memo table, where d is the digit count and s the target sum

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.