Dynamic Programming21 sections · 916 units
Open in Course

Pattern - Digit DP

Core idea

When you see a problem counting numbers in a range with digit-based constraints, think digit DP. The pattern:

1.1. Convert the limit to a string (base 1010) or binary.

2.2. State: (pos,tight,started,...extra)(pos, tight, started, ...extra) where extra depends on the constraint.

3.3. Transition: try each valid digit, update state, recurse.

4.4. Base case: return 11 when you've placed all digits (and satisfied constraints). Common extra states: bitmask (distinct digits), running sum (digit sum), remainder (divisibility), previous digit (adjacency constraints).