“How many numbers from 0 to a billion have digits summing to 20?” Looping to a billion is hopeless. Digit DP counts them by building numbers one digit at a time, left to right, and dynamic-programming over the choices. The crucial piece of state is a tight flag: is the prefix we’ve placed so far still exactly equal to N’s prefix? If it is, the next digit is capped at N’s digit; the moment we place something smaller, the rest of the positions are free to be anything, and their count follows from a small precomputed table. Watch the total assemble position by position.
O(digits × states) not O(N) · the “tight” flag caps digits to N · count, don’t enumerate
tight
True while the prefix equals N’s prefix — then the next digit is capped at N’s digit.
free
Once a smaller digit is placed, remaining positions can be anything (0–9).
property state
What you track to test the property — here the digit sum so far.
the count
Sum over positions of the free completions, plus N itself if it qualifies.
digit-dp.js — build a number, digit by digit
Ready
Counting numbers in [0, N] whose digits sum to S. We walk N’s digits left to right. At each position, placing a digit below N’s digit frees the rest — we add all free completions. Step through the positions.
–
position
–
added here
0
count so far
How it works
The insight is that once you deviate below N at some position, everything after is unconstrained — so you can count those completions in bulk instead of one by one. Precompute F[p][s] = how many p-digit strings have digit sum exactly s. Now walk N’s digits with a running sum. At position i, for each digit d strictly less than N’s digit there, the remaining positions are free, so add F[remaining][S − sumSoFar − d]. Then commit to N’s actual digit (staying tight) and move on. After the last position, if the accumulated sum equals S, add one for N itself. The total number of states is roughly digits × sum × 2, so this runs in the number of digits, not in N.
1
Precompute free completions
Build F[p][s] = the number of p-digit strings (each digit 0–9) whose digits sum to s. This lets you count unconstrained tails in one lookup.
2
Walk N’s digits, tracking the sum
Go left to right keeping the sum of digits placed so far, staying “tight” — equal to N’s prefix.
3
Below N’s digit → free the tail
At each position, for every digit smaller than N’s digit there, the remaining positions are free: add F[remaining][S − sumSoFar − digit]. Then set the digit to N’s and continue tight.
✓
Add N itself if it qualifies
After the last digit, if the tight number (N itself) has digit sum S, add one. The total is the count in [0, N] — computed in O(digits × states), never looping to N.
Time
O(digits × states)
vs brute
O(N)
Key state
“tight” flag
Counts
not enumerates
The code
# count numbers in [0, N] with digit sum == Sfrom functools import lru_cache
digits = list(map(int, str(N)))
@lru_cache(None)
def go(pos, cur_sum, tight):
if pos == len(digits):
return 1 if cur_sum == S else 0
hi = digits[pos] if tight else 9 # cap when tight
total = 0
for d in range(hi + 1):
total += go(pos + 1, cur_sum + d, tight and d == hi)
return total
answer = go(0, 0, True)
Quick check
1. What does the “tight” flag track in digit DP?
Tight means the prefix still equals N’s prefix. While tight, the next digit can’t exceed N’s digit at that position. The moment you place a smaller digit, you become “free” and the rest can be anything.
2. Why is digit DP faster than checking every number up to N?
Once a position goes below N’s digit, the remaining positions are unconstrained and their qualifying completions are counted in bulk from a table. So the work is proportional to digits × states — logarithmic in N, not linear.
3. After walking all of N’s digits while staying tight, what remains to check?
The tight path that never deviates spells out N exactly. It was never counted by the “place a smaller digit” branches, so at the end you add one if N itself satisfies the property.
FAQ
What is digit DP?
A DP technique for counting how many numbers in a range satisfy a digit-based property (target digit sum, no equal adjacent digits, divisibility…). It builds numbers digit by digit and memoizes over (position, a "tight" flag, property state), running in time proportional to the number of digits, not the range size.
What is the “tight” flag for?
It records whether the chosen prefix exactly matches N’s prefix. While tight, the next digit is capped at N’s digit (else you overshoot N). Placing a smaller digit makes you "free" — later positions can be 0–9. The flag is what keeps the count within [0, N].
What kinds of problems does digit DP solve?
Counting numbers in [L, R] by digit sum, adjacency constraints, divisibility (tracking remainder), containing/avoiding digits, palindromes, or bounded digit counts — with ranges via count(R) − count(L−1). A competitive-programming staple for counting by digit properties over huge ranges.
How do you handle a range [L, R] instead of [0, N]?
With the prefix trick: answer for [L, R] = count(R) − count(L−1), where count(x) is the digit-DP count in [0, x]. Any range reduces to two calls of the single-bound version, which is why digit DP is written to count up to one bound.
The picture: the tight path and the branches off it
Every number in [0, 327] either follows 3, 2, 7 all the way (only 327 itself does) or leaves that path at exactly one position by placing a smaller digit. Each branch hands the remaining positions to the table F in one lookup, so the count is a sum of at most 12 lookups instead of a loop over 328 numbers. A box turns red when none of its branches can reach the target.
Worked example, step by step
Count the integers in [0, 327] whose digits sum to 9. First build F[p][s], the number of p-digit strings (leading zeros allowed) with digit sum s: F[0][0] = 1, F[1][s] = 1 for s from 0 to 9, F[2][9] = 10, and so on. Then walk the digits of 327; each row is one smaller digit that could be placed at that position.
Position
Prefix sum
Digit placed (below N’s)
Free positions
Sum still needed
F lookup
Running total
1 (digit 3)
0
0
2
9
F[2][9] = 10
10
1 (digit 3)
0
1
2
8
F[2][8] = 9
19
1 (digit 3)
0
2
2
7
F[2][7] = 8
27
2 (digit 2)
3
0
1
6
F[1][6] = 1
28
2 (digit 2)
3
1
1
5
F[1][5] = 1
29
3 (digit 7)
5
0
0
4
F[0][4] = 0
29
3 (digit 7)
5
1
0
3
F[0][3] = 0
29
3 (digit 7)
5
2
0
2
F[0][2] = 0
29
3 (digit 7)
5
3
0
1
F[0][1] = 0
29
3 (digit 7)
5
4
0
0
F[0][0] = 1
30
3 (digit 7)
5
5
0
-1
F[0][-1] = 0
30
3 (digit 7)
5
6
0
-2
F[0][-2] = 0
30
Read the highlighted rows, the branches that contribute. At the first digit, placing 0, 1 or 2 leaves two free positions that must supply the rest of the sum, and F[2][s] counts exactly that: 10, 9, 8. At the second digit the prefix sum is 3, so placing 0 or 1 needs 6 or 5 more from one digit: 1 and 1. At the last digit the prefix sum is 5, so only the digits 0 to 4 can still reach 9, and each needs exactly one completion with zero free positions; digits 5 and 6 would need a negative remainder and contribute 0 (6 of the 12 rows are zeros). Finally the tight path spells 327, whose digits sum to 12, not 9, so it adds nothing. The total 30 matches a brute-force loop over all 328 numbers.
Complexity and trade-offs
Case
Time
Space
Why
Brute force loop
O(N · log N)
O(1)
Visit every number and sum its digits. Fine to about 10⁷, impossible at 10¹⁵.
Memoised recursion
O(D · S · 2 · 10)
O(D · S · 2)
D digits, sum up to S, a tight flag, ten digit choices. For N = 10¹⁵ and S = 30 the memo held 976 states.
Free-tail table + one walk
O(D · S · 10)
O(D · S)
Fill F once, then one lookup per smaller digit along a single path. The page’s method.
Range [L, R]
two calls
same
count(R) − count(L − 1): double the cost, no new idea.
Extra state (remainder, last digit)
multiplies by that state’s size
multiplies too
Divisibility by k adds k remainders; “no equal neighbours” adds the last digit (10 values).
The cost depends on the number of digits, not on the size of N: N = 10¹⁵ has 16 digits, and its memoised count needed 976 states against 10¹⁵ loop iterations. The price is that the property must be expressible as a small state updated one digit at a time. A digit sum, a remainder or the previous digit qualifies; “is prime” does not, because primality cannot be tracked in a few numbers as digits arrive.
Common mistakes
Forgetting to add N itself
The “place a smaller digit” branches never count N, because the tight path is not smaller than itself. For N = 100, S = 1 the walk alone gives 2; the right answer is 3 (1, 10 and 100). Check N at the end.
Keeping tight after leaving N’s prefix
Writing tight = (d == hi) instead of tight and d == hi re-tightens a free number whenever its digit happens to be 9. For N = 327, S = 18 that returns 4 instead of 6. Once a smaller digit is placed, tight stays false.
Leaving tight out of the memo key
The same (position, sum) has different futures when tight and when free, since the tight one is capped at N’s digit. Memoising on those two alone returns 7 for N = 100, S = 5, against the correct 6.
Subtracting count(L) instead of count(L − 1)
For the range 18 to 30 with digit sum 9 the matches are 18 and 27, so the answer is 2. count(30) − count(18) drops 18 and returns 1.
Counting leading zeros as digits
Padding 7 to 07 is harmless for a digit sum but wrong for “contains no zero”. Among 1 to 99 there are 90 numbers with no zero digit; a padded two-digit walk that treats the leading zero as a zero returns 81. Add a “started” flag to the state.
Where this shows up
Counting by digit properties
Numbers up to a bound with a given digit sum, with no two equal neighbours, never containing a banned digit, or whose digits are non-decreasing. Each is a small state advanced one digit at a time.
Divisibility inside a range
Add the running remainder modulo k to the state and the same walk counts multiples of k that also satisfy a digit rule. The state grows by a factor of k.
Summing, not just counting
Carry a pair (count, sum of values) per state and the walk can total the digit sums of every number up to N, or the sum of all qualifying numbers, with no change to the structure.
Ranks and k-th smallest
Run the walk in reverse: at each position, ask how many completions each digit leaves, and pick the digit whose cumulative count reaches k. That finds the k-th number with a property without enumerating the earlier ones.
SOLVE IT YOURSELF
Solve it: count without counting
How many numbers up to a trillion have digits summing to 30? Looping is hopeless. Build the number one digit at a time and memoise — the answer needs a few hundred states, not a trillion iterations. Python or TypeScript.
YOUR TASK
Implement count_with_digit_sum(N, S): how many integers in [0, N] have digits summing to exactly S.
HINTS — 7 IDEAS
Walk the digits of N left to right, choosing each digit of the candidate number as you go.
The state is (position, sum_so_far, tight). tight means every digit chosen so far exactly matched N’s.
While tight, this digit may only go up to N’s digit. Once you choose anything smaller, tight is false forever after and the remaining digits are free 0–9.
That single boolean is the whole trick — it is what keeps the count bounded by N without ever iterating to it.
Memoise on the state. Two different prefixes with the same position, running sum and tightness have identical futures, so the work collapses.
Prune when sum_so_far > S: nothing below can recover.
Leading zeros need no special handling here, because a leading zero contributes 0 to a digit sum — but for problems like "count numbers containing a 7" they would.