AdvancedDynamic Programming

Digit DP

Count numbers with constrained digits using tight/loose states

Time: O(d·S)
Space: O(d·S)
Pattern Overview

Core Idea

Traverse digits most-significant to least with a 'tight' flag and memoize (pos, tight, state...).

When to Use

Use for counting numbers ≤ N with properties (e.g., no consecutive ones, digit sums).

General Recognition Cues
General indicators that this pattern might be applicable
  • Count ≤ N
  • Digit constraints
  • Tight flag
Pattern Variants & Approaches
Different methodologies and implementations for this pattern
1

Tight/Loose States

Constrain next digit when tight

When to Use This Variant
  • Upper bound N
Use Case
Counting with cap
Advantages
  • Memoized recursion
Implementation
from functools import lru_cache
def count_no_consec_ones(n):
    s = bin(n)[2:]
    @lru_cache(None)
    def dp(i, tight, prev1):
        if i == len(s): return 1
        up = int(s[i]) if tight else 1
        total = 0
        for d in range(up + 1):
            if prev1 and d == 1: continue
            total += dp(i+1, tight and d==up, d==1)
        return total
    return dp(0, True, False)
2

Property Tracking

Carry state like prev digit/sum

When to Use This Variant
  • No consecutive 1s
Use Case
Pattern counts
Advantages
  • Flexible
Implementation
from functools import lru_cache
def count_digits_sum_leq(n, target):
    s=str(n)
    @lru_cache(None)
    def dp(i, tight, sum_):
        if i==len(s): return 1 if sum_<=target else 0
        up = int(s[i]) if tight else 9
        total=0
        for d in range(up+1):
            total += dp(i+1, tight and d==up, sum_+d)
        return total
    return dp(0, True, 0)
Common Pitfalls
Watch out for these common mistakes
  • Leading zeros handling
  • Tight transitions
  • State definition
Code Templates
Compare implementations across different languages
def template(*args, **kwargs):
    # General template placeholder
    pass
Example Problems
Classic LeetCode problems using this pattern
Complexity Analysis
Time Complexity
O(d·S)

Digits times state size.

Space Complexity
O(d·S)

Memo table size.

Ready to test your knowledge?

Test your pattern recognition with interactive questions