Digit DP
Count valid numbers by scanning upper-bound digits with tight and free suffix states.
Core idea
Scan the upper bound from most significant digit to least. A tight prefix may not exceed the bound digit; choosing a smaller digit releases every later position from that limit.
Read the visualization
The table separates free branches from the single tight path. Each row shows how many valid suffixes follow a smaller choice and whether matching the bound digit survives.
| at digit | available values | suffix 9^k | subtotal | |
|---|---|---|---|---|
| hundreds digit 2 | ||||
| tens digit 4 | ||||
| ones digit 5 | ||||
| total |
Split the upper bound into digits and begin in the tight prefix state.
Complexity and tradeoffs
Time: O(d × states × radix). Space: O(d × states). Memoization collapses all prefixes that share position, constraint state, and tightness.
Where it fits
Digit DP counts bounded integers with forbidden digits, digit sums, automaton constraints, and modular properties without enumerating the range.