Digit DP
O(digits · states)
Build the number digit by digit with a 'tight' flag tracking whether you're still bounded by the limit.
Learn first1D / Fibonacci-styleMath / Number Theory
0%
mastery
0/10 solved
0/10 solved
Recognise it
The signal
Count integers in [L, R] (N up to 1e18) whose digits satisfy a constraint; answer = f(R) - f(L-1).
1Brute force
Iterate every number up to N.
2The observation
Iterating N numbers: numbers sharing a prefix and state behave identically.
3Why it works
Once a prefix is strictly below N's prefix, the remaining digits are free and states can be memoised.
Reach for it when
- +N up to 1e18
- +answer = f(R) - f(L-1)
Not when
- ×Property depends on the whole number non-locally, not digit by digituse Math
- ×A closed-form combinatorial count existsuse Combinatorics
Practice
0/10 solved
- Count Numbers with Unique DigitsFoundationFoundationMedium
- Numbers At Most N Given Digit SetApply it · Upper bound N, digit set.Apply itHard
- Counting NumbersOne change · Range [a, b] with adjacent-digit constraint.One changeCSESMedium
- Number of Digit OneTwists · Count digits, not numbers.TwistsHard
- Numbers With Repeated DigitsBranches · Complement counting with a used-digit mask.BranchesHard
- Count of IntegersAdvanced · Two string bounds and a digit-sum window.AdvancedHard
- Magic NumbersMastery checkMastery checkCodeforces2200
- Writing NumbersCSESHard
- Removing Digits IICSESHard
- Count Special IntegersHard
Pitfalls
Classic bugs
- !Memoising tight states: only non-tight states are reusable; skip the cache (or key on
tight) when tight. - !Leading zeros can change the property (digit counts, 'no repeated digits'); track a
startedflag.
Go deeper1 combinations · resources
Combinations
count numbers <= N with all distinct (or repeated) digits
- Digit DP:
- the tight-prefix walk over the digits of N
- Bitmask DP:
- mask of digits already used