Digit dynamic programming
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Digit dynamic programming counts numbers in large ranges up to 10^18 that satisfy specific digit properties. We start with plain counting to see why checking numbers one by one is impossible.
Brute Force Iteration and Why It Fails
How would you count numbers up to N that have no duplicate adjacent digits or whose digit sum is divisible by 3? With plain iteration, you write a loop from 1 to N, extract the digits of each number, and test the condition.
Why does this fail? If N is 10^18, running a simple loop takes 10^18 iterations. At 1 billion operations per second, that loop would take over 30 years to finish!
Instead of checking existing numbers, digit DP builds numbers digit-by-digit from left to right. Because a 64-bit number has at most 19 digits, digit DP runs in mere milliseconds.
Prefix Counting and the Tight Flag
To count valid numbers in range [L, R], we evaluate solve(R) - solve(L - 1), reducing any range query to counting in [0, N]. We convert upper bound N into an array of its decimal digits.
Example 1 · Digit sum divisible by K, brute force: O(N · log N) time, O(1) space
public class DigitSumBruteDemo { static int count(int n, int k) { int total = 0; for (int x = 1; x <= n; x++) { // visit every number int sum = 0; for (int t = x; t > 0; t /= 10) sum += t % 10; if (sum % k == 0) total++; } return total; }
public static void main(String[] args) { System.out.println("Divisible by 3 up to 25: " + count(25, 3)); }}Divisible by 3 up to 25: 8
What this code does
- The outer loop visits N numbers; the inner loop strips one digit at a time, about log10(N) steps.
- It prints 8, the same as the digit DP, but N could be 10^18 and this loop would never finish.
Example 2 · Digit sum divisible by K with digit DP, optimal: O(L · K · 10) time, O(L · K) space
import java.util.Arrays;
public class DigitSumDivisibleDemo { private static int[][][] memo;
public static int count(int n, int k) { String s = String.valueOf(n); int len = s.length(); memo = new int[len][k][2]; for (int[][] a : memo) for (int[] b : a) Arrays.fill(b, -1); return dfs(s, 0, 0, 1, k) - 1; // subtract 0 }
private static int dfs(String s, int pos, int sumRem, int tight, int k) { if (pos == s.length()) return (sumRem == 0) ? 1 : 0; if (tight == 0 && memo[pos][sumRem][tight] != -1) { return memo[pos][sumRem][tight]; }
int limit = (tight == 1) ? (s.charAt(pos) - '0') : 9; int ans = 0;
for (int d = 0; d <= limit; d++) { int nextTight = (tight == 1 && d == limit) ? 1 : 0; ans += dfs(s, pos + 1, (sumRem + d) % k, nextTight, k); }
if (tight == 0) { memo[pos][sumRem][tight] = ans; } return ans; }
public static void main(String[] args) { System.out.println("Divisible by 3 up to 25: " + count(25, 3)); }}Divisible by 3 up to 25: 8
What this code does
- Tracks sumRem = (sum + d) % k as the only numerical property needed.
- When pos reaches s.length(), returns 1 if sumRem == 0 else 0.
- Up to 25, numbers 3, 6, 9, 12, 15, 18, 21, 24 have digit sum divisible by 3, totaling 8.
- Why faster: numbers with the same position and the same digit-sum remainder are counted together, so the loop over N numbers becomes a loop over its L digits.
When choosing a digit d at position pos, what is the maximum value d can take? If all preceding digits placed so far match the prefix of N, d is restricted: 0 <= d <= digits[pos]. This state is called tight. The moment we pick a digit d strictly less than digits[pos], tight flips to false. From that position forward, all remaining positions are completely free to pick any digit from 0 to 9.
Find the bug
Find the digit DP bug
Tap the line that breaks the count.
The next digit must stay "tight" only while every digit so far equals the limit.
Round 1 of 3Leading Zeros and Special Properties
Many digit properties (like having no adjacent duplicate digits) behave differently for formatting zeros compared to actual mathematical digits.
For example, the number 7 written in a 4-digit format is 0007. The initial zeros must not be treated as adjacent duplicate digits!
Example 3 · No equal neighbouring digits, brute force: O(N · log N) time, O(1) space
public class NoRepeatBruteDemo { static boolean valid(int x) { String s = String.valueOf(x); for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == s.charAt(i - 1)) return false; } return true; }
public static void main(String[] args) { int total = 0; for (int x = 1; x <= 100; x++) { // check every number if (valid(x)) total++; } System.out.println("Valid numbers up to 100: " + total); }}Valid numbers up to 100: 90
What this code does
- valid() compares each digit with the one before it.
- 11, 22, ..., 99 and 100 are rejected, so 90 of the 100 numbers remain.
- This is fine for 100 but far too slow for the large limits digit DP is made for.
Example 4 · No equal neighbouring digits with digit DP, optimal: O(L · 11 · 10) time, O(L · 11) space
import java.util.Arrays;
public class NoAdjacentDuplicatesDemo { private static int[][][] memo;
public static int countValid(int n) { String s = String.valueOf(n); int len = s.length(); memo = new int[len][11][2]; for (int[][] a : memo) for (int[] b : a) Arrays.fill(b, -1); return dfs(s, 0, 10, 1, 1) - 1; // subtract 0 }
private static int dfs(String s, int pos, int prevDigit, int tight, int leading) { if (pos == s.length()) return 1; if (tight == 0 && leading == 0 && memo[pos][prevDigit][leading] != -1) { return memo[pos][prevDigit][leading]; }
int limit = (tight == 1) ? (s.charAt(pos) - '0') : 9; int ans = 0;
for (int d = 0; d <= limit; d++) { if (leading == 0 && d == prevDigit) continue; // cannot match previous digit int nextTight = (tight == 1 && d == limit) ? 1 : 0; int nextLeading = (leading == 1 && d == 0) ? 1 : 0; int nextPrev = (nextLeading == 1) ? 10 : d;
ans += dfs(s, pos + 1, nextPrev, nextTight, nextLeading); }
if (tight == 0 && leading == 0) { memo[pos][prevDigit][leading] = ans; } return ans; }
public static void main(String[] args) { System.out.println("Valid numbers up to 100: " + countValid(100)); }}Valid numbers up to 100: 90
What this code does
- Uses prevDigit = 10 as sentinel representing no preceding numerical digit placed yet.
- Enforces d != prevDigit only when leading is 0.
- Up to 100, exactly 10 numbers have duplicate adjacent digits (11, 22, 33, 44, 55, 66, 77, 88, 99, 100), leaving 90 valid numbers.
- Why faster: once the number is below the limit, only the previous digit matters, so equal situations share one stored answer.
A boolean flag leadingZero stays true until the first non-zero digit is placed. Once any non-zero digit is selected, leadingZero flips to false, activating standard transition constraints.
Memoization Dimensions and State Caching
A standard digit DP state tuple is (pos, propertyState, tight, leadingZero). When tight is true, the current path matches the exact prefix of N and is visited at most once.
Therefore, we cache answers in memo[pos][propertyState] exclusively when tight is false and leadingZero is false.
Example 5 · Counting the digit one with digit DP: O(L² · 10) time, O(L²) space
import java.util.Arrays;
public class CountDigitOneDemo { private static int[][][] memo;
public static int countDigitOne(int n) { String s = String.valueOf(n); int len = s.length(); memo = new int[len][len + 1][2]; for (int[][] a : memo) for (int[] b : a) Arrays.fill(b, -1); return dfs(s, 0, 0, 1); }
private static int dfs(String s, int pos, int count1, int tight) { if (pos == s.length()) return count1; if (tight == 0 && memo[pos][count1][tight] != -1) { return memo[pos][count1][tight]; }
int limit = (tight == 1) ? (s.charAt(pos) - '0') : 9; int total = 0;
for (int d = 0; d <= limit; d++) { int nextTight = (tight == 1 && d == limit) ? 1 : 0; total += dfs(s, pos + 1, count1 + (d == 1 ? 1 : 0), nextTight); }
if (tight == 0) { memo[pos][count1][tight] = total; } return total; }
public static void main(String[] args) { System.out.println("Total 1s up to 13: " + countDigitOne(13)); }}Total 1s up to 13: 6
What this code does
- Accumulates the count of digit 1 encountered along each constructed path.
- At terminal position pos == s.length(), returns count1 directly.
- For n = 13, appearances are in 1, 10, 11 (two 1s), 12, 13, yielding 6 ones in total.
Because pos <= 18 and property states are typically small (sums <= 162), memoized digit DP computes answers instantaneously.
Next step
Check your understanding
10 quick questions