Digit DP: counting numbers up to N one digit at a time

Video lessonComing soon

1 Too many numbers to check

Some problems ask how many numbers from 1 to N follow a rule about their digits. The digits add up to k, or no digit is used twice, or every digit comes from a given set. N can be as large as 10¹⁸.

The % 10 loop from the extracting-digits lesson can check one number. But 10¹⁸ numbers of up to 19 digits each make around 10¹⁹ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).

Digit DP counts the numbers without listing them. It builds a number one digit at a time, from the left, and counts whole blocks of numbers at once.

The running example asks how many numbers from 1 to 325 have digits that add up to 5. There are 18:

51423324150104113122131140203212221230302311320
The 18 numbers up to 325 with digit sum 5

For a range from L to R, we count up to R and take away the count up to L − 1, as with prefix sums. So the rest of the lesson counts from 1 to N.

2 Setting the wheels of a lock

Picture a lock with one wheel per digit of N. For N = 325, the lock has three wheels, and every setting from 000 to 325 is one number. A shorter number has zeros in front, so 7 is 007. We set the wheels from left to right, and the lock must never read more than 325.

The first wheel can be 0, 1, 2 or 3. That choice decides how far the later wheels can turn:

How far each wheel can turn, N = 325
302152
N = 325
0–30?1?2pos
Wheel 0 can be 0 to 3, never more

So the lock is always in one of two modes:

  • Tight. Every wheel so far matches N. The next wheel can go only up to N's digit at that place.
  • Free. Some wheel went below N's digit. The number is already smaller than N, whatever comes next, so every later wheel has all ten choices.

A free lock never turns tight again. Only one setting stays tight all the way: N itself.

3 The state and the recursion

We count with a recursion that sets one wheel per call. Each call needs three things, and together they make the state:

  • pos: the wheel we are setting, from 0 on the left.
  • digitSum: the sum of the wheels set so far. This is what our rule needs.
  • tight: whether the wheels so far all match N.

A call tries each allowed digit on its wheel and adds up what the next calls return. When every wheel is set, the number counts if digitSum is k. A digit never lowers the sum, so a call returns 0 as soon as digitSum passes k.

countFrom(pos, digitSum, tight)
    if digitSum > k
        return 0
    if pos == number of digits in N
        return 1 if digitSum == k, else 0
    limit = N's digit at pos if tight, else 9
    count = 0
    for digit from 0 to limit
        stillTight = tight and digit == limit
        count += countFrom(pos + 1, digitSum + digit, stillTight)
    return count

The first call is countFrom(0, 0, true). It is tight, because no wheel has gone below N yet.

A free call's answer depends only on how many wheels are left and how much sum they still need. The settings 01? and 10? both leave one free wheel that needs 4, so they ask the same question. As in the DP lesson, we save each free answer in memo[pos][digitSum].

A tight call never repeats, because only one prefix matches N. It needs no memo, and section 7 shows why it must stay out of it.

4 Tracing N = 325, k = 5

The first call sets wheel 0 to each of 0, 1, 2 and 3. The rows below are those four calls, then the three calls under the tight one:

Wheels setdigitSumtightNext wheelCount
00no0–96
11no0–95
22no0–94
33yes0–23
3, 03no0–91
3, 14no0–91
3, 25yes0–51

The first four counts add up to 6 + 5 + 4 + 3 = 18. The first three rows are free, so each one counts a whole block of numbers. The 0 row counts 5, 14, 23, 32, 41 and 50, and the 1 row counts every number from 100 to 199 with digit sum 5. Only the tight row has to split again. Its three rows count 302, 311 and 320, and only the last stays tight.

The memo pays off inside the free rows. After 0 then 1, the call for (pos 2, sum 1) saves its answer. Later, 1 then 0 asks for the same state and reads it back. On this small N, the memo cuts the calls from 214 to 104. Without the memo, the recursion walks every free block one number at a time, and that is the slow loop again.

5 The code and its cost

countUpTo counts the numbers from 0 to n, and countInRange takes away the count below low. Zero has digit sum 0, so it never counts for k ≥ 1. The code keeps N's digits as a string, so digits[pos] is wheel pos read from the left.

On 1 to 325 with k = 5, every tab returns 18. On 100 to 325 it returns 18 − 6 = 12.

C++

Digits from to_string. n is a long long, which holds up to about 9 × 10¹⁸. to_string(n) gives its digits from the left, and digits[pos] - '0' turns one into a number.

Digits from Long.toString. n is a long, which holds up to about 9 × 10¹⁸. charAt(pos) - '0' turns one digit into a number.

Nothing to watch. Python's integers grow as needed, and str(n) gives the digits from the left.

Exact only up to about 9 × 10¹⁵. A JavaScript number loses its last digits past that. Up to N = 10¹⁸ with k = 81, the count is about 3 × 10¹⁶, so take N as a string and keep the counts as BigInt there.

Digits from strconv.FormatInt. n is an int64, which holds up to about 9 × 10¹⁸. digits[pos] - '0' turns one byte into a number.

Digits as bytes. n.to_string().into_bytes() gives the digits from the left, and digits[pos] - b'0' turns one into a number. The memo, the digits and k travel as arguments, because a closure cannot call itself.

Digits from ToString. n is a long, which holds up to about 9 × 10¹⁸. digits[pos] - '0' turns one digit into a number.

Let D be the number of digits of N. There are at most D × (k + 1) free states, and each tries 10 digits. N = 10¹⁸ has 19 digits, and digitSum can never be more than 9 × 19 = 171. So there are about 3,300 states and around 3 × 10⁴ steps, which is tiny. The time is O(D × k × 10), and the memo takes O(D × k) space.

6 Leading zeros and other rules

The lock writes 7 as 007. For a digit sum, those zeros are harmless: a 0 adds nothing, so 007 and 7 have the same sum.

Other rules do notice them. Take the numbers with no digit used twice, as in Count Special Integers. The number 7 has no repeat, but 007 has two 0s. Up to N = 100, 90 numbers have no repeat, but a count over the padded settings gives 72.

The fix is one more part of the state, started: whether a wheel before this one was set to something other than 0. Until then, a 0 is a blank wheel, not a digit, and the rule ignores it.

Each rule changes only what the state carries. pos and tight are always there:

RuleExtra stateLeading zeros
Digits add up to ksum so farharmless
How many 1s in all the numbers1s so farharmless
No digit used twicedigits used so farneed started
Only digits from a given setnoneneed started

The digits used so far fit in a 10-bit mask, one bit per digit. The bitmask DP lesson keeps a set of used items the same way.

7 Mistakes and edge cases

  • count(R) − count(L). This takes away L itself. On 104 to 325 with k = 5, it gives 18 − 7 = 11 instead of 12, because 104 has digit sum 5 and is lost.
  • Saving tight answers in the memo. A tight call and a free call can share pos and digitSum but not their answer. On N = 320 with k = 6, the free state (pos 2, sum 5) lets the last wheel be 0 to 9 and counts 1. The tight call after 32 allows only 0 and should count 0. If it reads the saved 1, it counts 321, and the answer is 21 instead of 20. Keep tight calls out of the memo, or put tight in its key.
  • Taking digits with % 10. That gives them from the right, but the wheels go from the left, and the tight check compares from the left. Convert N to a string, or reverse the digits first.
  • N in a 32-bit int. N up to 10¹⁸ needs a 64-bit integer, and so does the count.

8 When to use digit DP

The sign is a count of numbers up to a huge bound, often 10⁹ to 10¹⁸, where the rule is about each number's digits. Looping up to the bound is too slow, but the bound has at most 19 digits.

To set one up, answer three questions:

  • What does the rule need to remember about the wheels set so far? That, with pos and tight, is the state.
  • Do leading zeros change the rule? If they do, add started.
  • Is it a range? Count up to R and take away the count up to L − 1.

When the problem counts every number below 10ⁿ, the bound is all nines, so tight never limits a wheel. Such problems often have a direct formula.

Before looping up to N, look at how big N is. If it is far past 10⁸ and the rule is about digits, set the wheels instead.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.