Lesson 26 · Problem-solving methods

Digit Dynamic Programming

Digit DP counts how many numbers up to a bound N have some digit property, such as a given digit sum, by choosing digits from left to right. The number of states depends on the number of digits, not on N, so bounds like 10¹⁸ are easy.

Digit Dynamic Programming concept diagramA visual explanation of the layout and operations shown in this lesson.count by prefix, carrying one flag: is the prefix still tight?257limit N = 257 — fix digits left to righttight: 0..2free: 0..9choosing the max digit keeps the prefix tight— the next position is still cappedchoosing anything smaller frees it— every later digit may be 0..9
1

What Digit DP Counts

Digit DP answers questions of the form: how many integers x with 0 ≤ x ≤ N have some property of their digits? Typical problems: digit sum equal to k, no two equal adjacent digits, no repeated digits, divisible by m, or how many times the digit 1 appears (LeetCode 233, Number of Digit One).

Checking every number is O(N), hopeless for N = 10¹⁸. Digit dynamic programming builds the numbers one digit at a time from the left and groups all prefixes that behave the same from then on. The work grows with the number of digits (19 for 10¹⁸) times the size of the property, not with N. It is a form of dynamic programming, usually written top-down with memoization.

  • Questions about digits of every number up to N
  • Cost depends on the digit count, not on N
2

The State and the Recursion

  1. Write the bound N as a digit string
  2. At each position, try digits 0 to the limit
  3. Update the property (sum, remainder, last digit) and the tight flag
  4. At the end of the string, return 1 if the property holds, else 0
  5. Memoize on (position, property, tight)

A state holds three things: the position in the digit string, what the property still needs (the remaining digit sum, the remainder so far, the last digit), and the tight flag. Two prefixes with the same state have exactly the same set of valid endings, so their count is computed once.

For N = 325 and digit sum 5: hundreds digit 0, 1 or 2 leaves two free digits needing 5, 4 or 3 (6, 5 and 4 ways). Hundreds digit 3 stays tight and allows only 302, 311 and 320. The total is 18. The tracer walks through each state.

  • Same state, same set of endings
  • Only store what decides the future
3

The Tight Flag

Tight is true while the digits chosen so far equal the bound's first digits. Then the next digit may be at most the bound's digit at that position; otherwise it may be anything from 0 to 9. The update is new tight = tight and digit == limit: choosing a smaller digit makes the number smaller than N whatever follows, so the flag turns false and never comes back.

Both mistakes are common. Dropping the flag counts numbers above N (for 325 it counts 401, 410 and 500, giving 21). Keeping the limit after a smaller digit misses valid numbers like 50 and 140, giving 12. Tight states lie on a single path down the bound, so almost all the work happens in loose states.

  • Smaller digit: tight turns off for good
  • Equal digit: tight stays on
Key reference

Terms, operations, and practical uses

Bound state

  • PositionIndex of the next digit to choose in the bound's digit string, from the most significant digit.
  • Tight flagTrue while the prefix equals the bound's prefix. Caps the next digit at the bound's digit.
  • LimitThe largest digit allowed next: the bound's digit when tight, otherwise 9 (or base − 1).

Property state

  • Need / sumWhat the property still requires, for example the digit sum left to reach. Bounded by 9 × digits.
  • Started flagFalse until the first non-zero digit, so padding zeros do not count as digits.
  • Remainder(old × 10 + digit) mod m tracks divisibility without storing the number itself.

Range counting

  • F(N)Count of valid numbers from 0 to N, the quantity one digit DP run computes.
  • F(R) − F(L − 1)Count in [L, R]. Use F(R) alone when L = 0.
  • Loose-state cacheStates with tight false do not depend on the bound, so their memo can be shared across bounds.
Implementation

Code in Python, C++ and Java

from functools import lru_cache


def count(n, target):
    if n < 0:
        return 0
    digits = list(map(int, str(n)))

    @lru_cache(None)
    def go(pos, need, tight):
        if need < 0:
            return 0
        if pos == len(digits):
            return 1 if need == 0 else 0
        limit = digits[pos] if tight else 9
        return sum(go(pos + 1, need - d, tight and d == limit) for d in range(limit + 1))

    return go(0, target, True)


print("Up to 325:", count(325, 5))
print("In [100, 325]:", count(325, 5) - count(99, 5))
#include <cstring>
#include <iostream>
#include <string>
using namespace std;

string digits;
long long memo[20][200][2];

long long go(int pos, int need, int tight) {
    if (need < 0) return 0;
    if (pos == (int)digits.size()) return need == 0;
    long long &res = memo[pos][need][tight];
    if (res != -1) return res;
    res = 0;
    int limit = tight ? digits[pos] - '0' : 9;
    for (int d = 0; d <= limit; d++) res += go(pos + 1, need - d, tight && d == limit);
    return res;
}

long long countUpTo(long long n, int target) {
    if (n < 0) return 0;
    digits = to_string(n);
    memset(memo, -1, sizeof memo);
    return go(0, target, 1);
}

int main() {
    cout << "Up to 325: " << countUpTo(325, 5) << '\n';
    cout << "In [100, 325]: " << countUpTo(325, 5) - countUpTo(99, 5) << '\n';
}
import java.util.*;

class Main {
    static String digits;
    static Long[][][] memo;

    static long go(int pos, int need, int tight) {
        if (need < 0) return 0;
        if (pos == digits.length()) return need == 0 ? 1 : 0;
        if (memo[pos][need][tight] != null) return memo[pos][need][tight];
        long res = 0;
        int limit = tight == 1 ? digits.charAt(pos) - '0' : 9;
        for (int d = 0; d <= limit; d++) res += go(pos + 1, need - d, tight == 1 && d == limit ? 1 : 0);
        return memo[pos][need][tight] = res;
    }

    static long countUpTo(long n, int target) {
        if (n < 0) return 0;
        digits = Long.toString(n);
        memo = new Long[20][200][2];
        return go(0, target, 1);
    }

    public static void main(String[] args) {
        System.out.println("Up to 325: " + countUpTo(325, 5));
        System.out.println("In [100, 325]: " + (countUpTo(325, 5) - countUpTo(99, 5)));
    }
}
Watch it run

Step through it

Running on bound = 325, digit sum = 5

count x in [0, 325] with digit sum 5bound325digit sum = 5startneed 5 · tightmemo: loose states012345need2 left1 leftstate: digits left, need, tighttight = prefix equals 3, 32, ...start: 3 digits left, need 5, tight
Step 1

Bound 325, digit sum 5

Instead of testing all 326 numbers, digit DP builds them digit by digit from the left. The state is how many digits are left, how much digit sum is still needed, and whether the prefix so far equals the bound's prefix (tight). At the start nothing is chosen, so the prefix is tight.

Output
1 / 10
4

Leading Zeros

Writing every number with the bound's length pads short numbers with zeros: 7 becomes 007. For a digit sum this is harmless, but for properties like "no digit 0", "no two equal adjacent digits" or "count of zeros" the padding zeros would be read as real digits.

A started flag fixes this. It is false until the first non-zero digit; while it is false, a 0 is padding and does not touch the property. Counting [1, 325] with no digit 0 gives 266 with the flag and 176 without it, which loses every one- and two-digit number. Decide separately whether the number 0 itself should be counted.

  • Padding zeros are not digits
  • Decide whether 0 counts
5

Counting a Range

Write F(N) for the count from 0 to N. Then a range is F(R) − F(L − 1). For digit sum 5, F(325) = 18 and F(99) = 6, so [100, 325] holds 12. If L is 0, use F(R) alone instead of building the digits of −1.

Bounds up to 10¹⁸ fit in a 64-bit integer, but problems often give them as strings with hundreds of digits; the method works on the string directly. To compute L − 1 for a string, subtract 1 by hand or count [L, R] as F(R) − F(L) plus a check of L itself.

  • F(R) − F(L − 1)
  • Work on the digit string, not the integer
6

Complexity and Testing

Time is positions × property states × 2 (tight) × 10 (digits). For N up to 10¹⁸ and a digit sum target, that is about 19 × 172 × 2 × 10 ≈ 65,000 steps. Remainder mod m multiplies by m; tracking a set of used digits multiplies by 2¹⁰ = 1,024. Work out this product before coding.

If the memo key leaves out tight, cache only loose states, which do not depend on the bound and can be reused across many bounds. Test against brute force for every N up to a few thousand, and pay attention to 0, powers of ten, numbers of all 9s, and L = R; off-by-one errors cluster at 99 → 100.

  • Multiply all state sizes before coding
  • Brute-force every bound up to a few thousand