Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Dynamic Programming

Count by Digits.

“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 == S from 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?

2. Why is digit DP faster than checking every number up to N?

3. After walking all of N’s digits while staying tight, what remains to check?

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

N = 327, S = 9327tight pathplace below 30 → F[2][9] = 101 → F[2][8] = 92 → F[2][7] = 8place below 20 → F[1][6] = 11 → F[1][5] = 1place below 74 → F[0][0] = 10, 1, 2, 3, 5, 6 → 010 + 9 + 8 + 1 + 1 + 1 + 0 (N itself, digit sum 12) = 30
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.

PositionPrefix sumDigit placed (below N’s)Free positionsSum still neededF lookupRunning total
1 (digit 3)0029F[2][9] = 1010
1 (digit 3)0128F[2][8] = 919
1 (digit 3)0227F[2][7] = 827
2 (digit 2)3016F[1][6] = 128
2 (digit 2)3115F[1][5] = 129
3 (digit 7)5004F[0][4] = 029
3 (digit 7)5103F[0][3] = 029
3 (digit 7)5202F[0][2] = 029
3 (digit 7)5301F[0][1] = 029
3 (digit 7)5400F[0][0] = 130
3 (digit 7)550-1F[0][-1] = 030
3 (digit 7)560-2F[0][-2] = 030

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

CaseTimeSpaceWhy
Brute force loopO(N · log N)O(1)Visit every number and sum its digits. Fine to about 10⁷, impossible at 10¹⁵.
Memoised recursionO(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 walkO(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 callssamecount(R) − count(L − 1): double the cost, no new idea.
Extra state (remainder, last digit)multiplies by that state’s sizemultiplies tooDivisibility 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
  1. Walk the digits of N left to right, choosing each digit of the candidate number as you go.
  2. The state is (position, sum_so_far, tight). tight means every digit chosen so far exactly matched N’s.
  3. 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.
  4. That single boolean is the whole trick — it is what keeps the count bounded by N without ever iterating to it.
  5. Memoise on the state. Two different prefixes with the same position, running sum and tightness have identical futures, so the work collapses.
  6. Prune when sum_so_far > S: nothing below can recover.
  7. 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.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextHalving the Exponential: Meet in the Middle Next on the “When the state is not a number” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms