Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/Digit DP

Learn the pattern · ~15 min

Digit DP

To count numbers up to a huge N by a rule about their digits, build them one digit at a time with a tight flag and a small state; once you drop below N's prefix the rest is free, and equal states have equal counts.

Signalscount integers in [L, R] whose digits satisfy somethingN up to 1e18answer = f(R) - f(L-1)Learn first1D / Fibonacci-styleMath / Number Theory
Cheat sheet and practice

Reach for it when you read

  • +Count the numbers in [L, R], with R up to 10¹⁸, whose digits follow a rule: all distinct, no two neighbours equal, digit sum k.
  • +Add something up over all numbers ≤ N: how many 1s appear in total.
  • +Count numbers ≤ N written only with a given set of digits.
  • +Count numbers ≤ N that are divisible by m and have a digit rule.

Not this one when

  • ×N is about 10⁶ or less: loop over the numbers and test each one.
  • ×The rule is about the value, not the digits (primes, squares): a sieve or a formula.
  • ×Multiples of m with no digit rule: the answer is N / m.

Learn Digit DP

First, what is digit DP?

Digit DP counts the numbers from 1 to N whose digits follow a rule (all different, no 4s, digit sum 10…) without visiting them one by one. It builds each number digit by digit, left to right.

To compare numbers of different lengths, pad them all to N's length with leading zeros: with N = 320, the number 7 is written 007 and 45 is 045.

The new word is tight. A prefix is tight when it has copied N's digits exactly so far. Then its next digit can't go above N's next digit, or the number would pass N. The moment a digit goes below N's, the prefix is free: everything after it can be 0 to 9.

Building every number ≤ 320

Count all of them, 000 to 320. The rule:

If you're tight, the next digit goes up to N's digit, and you stay tight only by copying it. If you're free, the next digit is 0 to 9 and you stay free.

prefix what happens tight? numbers
0, 1, 2 below N's 3: the last two digits are free, 10 · 10 no 3 · 100 = 300
3 copied N's 3, so the next digit goes up to 2 yes
30, 31 below N's 2: the last digit is free no 2 · 10 = 20
32 copied again, so the last digit goes up to 0 yes
320 copied every digit yes 1

300 + 20 + 1 = 321 numbers, 0 to 320. Only one path stays tight all the way: N itself.

The code for it

C++
long long all(int pos, bool tight) {        // how many ways to finish from here
    if (pos == (int)D.size()) return 1;     // a whole number is written
    int hi = tight ? D[pos] - '0' : 9;      // the ceiling for this digit
    long long total = 0;
    for (int d = 0; d <= hi; d++)
        total += all(pos + 1, tight && d == hi);   // stay tight only by copying N's digit
    return total;
}
// all(0, true) counts 0 to N

You don't need to memorise this. It's the table above: the ceiling is N's digit while tight, 9 once free.

Why tight && d == hi? Once a digit drops below N's, no later digit can lift the number above N, so only a tight prefix that copies N's digit stays tight.

Fine, but how does this help us?

Here's a classic problem: Count Special Integers. How many numbers in [1, N] have no repeated digit? For N = 320, count by hand:

numbers how you count them count
1 to 9 every one-digit number 9
10 to 99 first digit 1–9, second any of the other 9 9 · 9 = 81
1__ 9 choices for the middle (not 1), then 8 9 · 8 = 72
2__ same as 1__ 72
30_, 31_ the last digit avoids the two used: 8 each 16
320 3, 2, 0 are all different 1

9 + 81 + 72 + 72 + 16 + 1 = 251.

The brute force

The choices: the next digit, 0 to 9 (or up to N's digit while tight). Carry what the rule needs: a 10-bit mask of the digits used so far, and started, which says whether a non-zero digit has been written yet.

C++
long long go(int pos, int mask, bool tight, bool started) {
    if (pos == (int)D.size()) return started ? 1 : 0;      // 0 isn't counted
    int hi = tight ? D[pos] - '0' : 9;
    long long total = 0;
    for (int d = 0; d <= hi; d++) {
        if (started && (mask >> d & 1)) continue;           // the rule: no repeats
        bool now = started || d != 0;                       // leading zeros aren't digits
        int next = now ? mask | 1 << d : mask;
        total += go(pos + 1, next, tight && d == hi, now);
    }
    return total;
}
// answer: go(0, 0, true, false)

Draw a corner of the calls:

  • go("", tight)
    • 1 → go("1", free)
      • 0 → go("10") …
      • 2 → go("12", free) → 0, 3, 4, 5, 6, 7, 8, 9: 8 numbers
    • 2 → go("2", free)
      • 1 → go("21", free) → 0, 3, 4, 5, 6, 7, 8, 9: 8 numbers← the same work
    • 3 → go("3", tight) → "30", "31", "32" (tight) → "320"

Correct, and for this rule even fast: a repeat kills its branch at once, so the leaves are only the numbers with all-different digits, under 9 × 10⁶. N = 2 × 10⁹ takes 0.04 s. Change the rule to one that cuts nothing, like "divisible by 3", and every number ≤ N is a leaf: 3.4 s at N = 2 × 10⁹, hopeless at 10¹⁸. Time limit exceeded.

The one thought: free prefixes forget what they were

Point at "12" and "21". Both are free (below 32), both have used the digits {1, 2}, and both have one digit left.

Can the rule tell them apart? No. It only asks "is this digit used already?", and both have the same set. So each finishes the same 8 ways. Only the position, the digits used and started matter.

Tight prefixes do differ, since their ceiling depends on N. But there's one tight prefix per length, so they never repeat. Memoise free states only.

Memoise it

C++
long long memo[20][1 << 10][2];   // -1 = not computed
long long count(int pos, int mask, bool tight, bool started) {
    if (pos == (int)D.size()) return started ? 1 : 0;
    if (!tight && memo[pos][mask][started] != -1) return memo[pos][mask][started];
    int hi = tight ? D[pos] - '0' : 9;
    long long total = 0;
    for (int d = 0; d <= hi; d++) {
        if (started && (mask >> d & 1)) continue;
        bool now = started || d != 0;
        int next = now ? mask | 1 << d : mask;
        total += count(pos + 1, next, tight && d == hi, now);
    }
    if (!tight) memo[pos][mask][started] = total;   // only free states are shared
    return total;
}
// upTo(N): D = to_string(N); memset(memo, -1, sizeof memo); return count(0, 0, true, false);

What the memo holds

The code is top-down: an entry is written when its call returns, so states with the fewest digits left are stored first. For this rule a started free state's value depends only on the digits left and how many are used:

digits left 1 digit used 2 digits used what happens
0 1 1 the number is finished: count it
1 9 8 any digit not used yet
2 72 56 9 · 8 and 8 · 7

"12_" is (1 left, 2 used): 8, and "1__" is (2 left, 1 used): 72, the numbers from the hand count. The memo itself is keyed by the exact set, though: {1} and {2} are two entries that happen to hold the same 72.

Dry run

N = 320, from the top call:

first digits tight? what happens numbers counted
0 (not started) no leading zero, so it's the 1- and 2-digit numbers 90
1__ no computed; each 1x is stored 72
2__ no 21 finds the 8 stored for 12 (same set {1, 2}); the rest are new 72
30_, 31_ no 31 finds the 8 stored for 13; 30 is new 8 + 8
32_ → 320 yes, to the end the one tight path 1
total 251

251, the same answer as the brute force. On 320 the memo saves only two calls; on long N, about 2 × 10⁴ free states cover billions of numbers.

Why it's fast

Count free states: at most 10 positions × 2¹⁰ masks × 2 values of started, about 2 × 10⁴, each trying 10 digits: about 2 × 10⁵ steps. The tight path adds one call per position.

From one leaf per number down to about 2 × 10⁵ steps, by remembering free states instead of numbers.

A range [L, R]? Subtract

Count up to R, then take away everything below L:

C++
long long answer = upTo(R) - upTo(L - 1);

Distinct digits in [100, 320]: 251 − 90 = 161.

Remember this

  • State = what the rule needs about the prefix (the digits used, or a remainder (rem * 10 + d) % m), plus tight. Memoise only free states.
  • Trap: leading zeros. Without started, 7 is 007 with two 0s and gets thrown out: N = 320 gives 233 instead of 251.
  • Trap: a range is upTo(R) − upTo(L − 1), not upTo(R) − upTo(L).
  • Whenever a problem asks how many numbers ≤ N (or in [L, R]) pass a rule about their digits, with N up to 10¹⁸, it's this.

Practise it on Count Numbers with Unique Digits (no bound yet), then Numbers At Most N Given Digit Set, Count Special Integers, Numbers With Repeated Digits (count the complement), Number of Digit One (a sum) and Count of Integers (a range of huge numbers).

Watch it work, line by line

Count Numbers With No Repeated Digit ↗, N = 25 → 23 (every number except 11 and 22). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Am I counting numbers up to a huge N (10⁹, 10¹⁸, or a long string) by a rule I can check digit by digit with a small state?

Reach for it when

  • +count integers in [L, R] whose digits satisfy something
  • +N up to 1e18
  • +answer = f(R) - f(L-1)
  • +N up to 1e18 (19 digits); property state small

It fails when

  • ×Property depends on the whole number non-locally, not digit by digituse Math
  • ×A closed-form combinatorial count existsuse Combinatorics

Looks like it, isn't (and the other way round)

  • Count Special Integers looks like Combinatorics mod p (nCr, Catalan, stars and bars), needs this pattern

    Counting distinct-digit numbers <= n needs a tight-prefix walk plus a used-digit mask (digit DP with bitmask).

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why are tight states never saved in the memo?Reveal

    Their limit comes from N's own digits, so only N's prefix ever reaches them. A free state with the same position and mask has a different count.

  • 2Why track started for "all digits different"?Reveal

    Leading zeros aren't digits of the number. Without the flag, for N = 100 the number 10 is built as 010 and wrongly rejected for repeating 0.

  • 3How do you count a range [L, R]?Reveal

    count(R) − count(L − 1), using one "count up to N" function.

Practice ladder

every problem →
  1. 1Count Numbers with Unique Digitsno bound yetMedium
  2. 2Numbers At Most N Given Digit Setallowed digitsHard
  3. 3Counting Numbersneighbour ruleMedium
  4. 4Count Special Integersthe hookHard
  5. 5Numbers With Repeated DigitscomplementHard
  6. 6Number of Digit Onea sumHard
  7. 7Count of Integersa rangeHard
  8. 8Magic Numbersdivisibility2200

Finished Digit DP? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Digit DP

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial