Digit DP
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Digit DP counts how many numbers up to a limit follow some rule about their digits, without looking at every number. You build the number one digit at a time and remember only a few small facts, such as the digit sum so far, so a billion candidates collapse into a few thousand situations.
Practical use cases
- Web app: Lucky coupon codes under a limit. A marketing page hands out numeric coupon codes from 1 to 99,999,999, and the rule says a code is "lucky" if it never contains the digit 7. The admin dashboard must show how many lucky codes exist. Looping over a hundred million numbers freezes the report, but building a code digit by digit and remembering only "have I already gone below the limit?" gives the count in a blink.
- Web app: Counting valid ticket or invoice numbers. A billing system numbers invoices so the digits must add up to a multiple of 9 as a typo check. Finance asks how many valid invoice numbers fit between 1 and 5,000,000. Instead of testing each number in a PHP loop, you count by position, keeping only the running digit sum, which turns minutes of looping into a few thousand small steps.
- System: Contest and analytics puzzles about digits. Questions like "how many numbers up to N have no two equal neighbouring digits" show up in coding contests and in data checks on huge serial-number ranges. The same digit-by-digit counting answers them even when N has eighteen digits, which no loop could ever finish.
The story: The Lift That Skips Seven
A new apartment tower in Mumbai had a superstitious builder: no flat number may contain the digit 7. The flats were numbered 1 to 235. The society secretary asked Kabir, "How many flats can we actually sell?" Kabir started listing numbers and checking each digit. Then she asked the same question for 1 to a hundred million. He quit.
Mira said, "We don't need to look at every number. Look at the digits of the limit, left to right." At the first place, any digit smaller than 2 (0 or 1) puts us safely below 235, and after that anything goes, apart from 7. So the rest of the digits are free: 9 choices each, which is a quick lookup. Then take the digit 2 itself and move on to the next place, where the same idea repeats.
We only remember two things at each place: which place we are at, and whether we are still hugging the limit (tight) or already below it (free). That is why it is a DP: many numbers share the same small state. This is Digit DP. Honest note: counting "no digit 7" is the smallest example. Harder versions add one more fact, such as the digit sum so far, but the walk stays exactly the same.
How to spot this problem, and where you need it
You must count (or sum) numbers in a huge range that satisfy a rule about their digits, and the range is so big that checking each number one by one would take forever.
Signs you need it
- The problem says "how many numbers from 1 to N" where N can be a billion or more, and the rule talks about digits (digit sum, no digit 7, no repeated digits).
- Your brute-force loop works for N = 10,000 in testing but would run for hours or days for the real limit.
- The answer for a number only depends on a few facts about its digits so far, such as the sum, the last digit, or whether a zero has appeared.
- You catch yourself converting numbers to strings inside a giant loop just to inspect their digits.
Where to use it in a project
- Reports that count valid serial numbers, coupon codes or ticket ids inside a numeric range.
- Validation tools that count how many identifiers under a limit pass a checksum-style digit rule.
The solution
Write the limit as a list of digits. Walk left to right choosing each digit for the new number, and keep a flag "still tight to the limit". While tight, you may not exceed the limit digit; the moment you pick a smaller digit you are free and may pick anything. Remember the small facts you need (like the digit sum) and store the answer for each (position, facts, tight) situation so it is never recomputed. This is digit DP.
Payoff: Before: checking 100,000,000 numbers one by one. After: a few thousand remembered situations, so the report returns instantly.
Explain it like I am 8
Imagine writing numbers on a slate digit by digit, never allowed to go above the limit. The moment you write a digit smaller than the limit's digit, you are free to write anything after it. So you can count a whole bunch of numbers in one go instead of one by one.
How it works, step by step
- Split the limit into digits: 235 → [2, 3, 5].
- The state is (place, tight). Tight means every digit so far matches the limit; free means we are already below it.
- At each place the largest allowed digit is the limit's digit when tight, otherwise 9. Skip forbidden digits (7).
- Choosing a digit smaller than the limit makes us free; choosing exactly the limit digit keeps us tight.
- Remember (cache) the answer for each state so it is computed once. Past the last place, return 1 (a good number was built).
- Our count includes the number 0, so subtract 1 if you only want 1..N.
The code in four languages
PHP
<?php
// Count numbers from 1 to $n that contain no digit 7, using digit DP.
function countNoSeven(int $n): int {
$d = array_map('intval', str_split((string)$n)); // digits of the limit
$len = count($d);
$memo = [];
$go = function (int $pos, bool $tight) use (&$go, &$memo, $d, $len): int {
if ($pos === $len) return 1; // built one valid number (maybe 0)
$key = $pos * 2 + ($tight ? 1 : 0);
if (isset($memo[$key])) return $memo[$key];
$limit = $tight ? $d[$pos] : 9; // tight: cannot exceed the limit's digit
$total = 0;
for ($x = 0; $x <= $limit; $x++) {
if ($x === 7) continue; // forbidden digit
$total += $go($pos + 1, $tight && $x === $limit);
}
return $memo[$key] = $total;
};
return $go(0, true) - 1; // remove the number 0
}
$fast = countNoSeven(235);
$slow = 0;
for ($i = 1; $i <= 235; $i++) if (strpos((string)$i, '7') === false) $slow++;
echo $fast, ' ', $slow, "\n"; // 194 194JavaScript
// Count numbers from 1 to n that contain no digit 7, using digit DP.
function countNoSeven(n) {
const d = String(n).split('').map(Number); // digits of the limit
const memo = new Map();
function go(pos, tight) {
if (pos === d.length) return 1; // built one valid number (maybe 0)
const key = pos * 2 + (tight ? 1 : 0);
if (memo.has(key)) return memo.get(key);
const limit = tight ? d[pos] : 9; // tight: cannot exceed the limit's digit
let total = 0;
for (let x = 0; x <= limit; x++) {
if (x === 7) continue; // forbidden digit
total += go(pos + 1, tight && x === limit);
}
memo.set(key, total);
return total;
}
return go(0, true) - 1; // remove the number 0
}
const fast = countNoSeven(235);
let slow = 0;
for (let i = 1; i <= 235; i++) if (!String(i).includes('7')) slow++;
console.log(fast + ' ' + slow); // 194 194Java
import java.util.*;
public class Main {
static int[] d; // digits of the limit
static Map<Integer, Integer> memo = new HashMap<>();
static int go(int pos, boolean tight) {
if (pos == d.length) return 1; // built one valid number (maybe 0)
int key = pos * 2 + (tight ? 1 : 0);
if (memo.containsKey(key)) return memo.get(key);
int limit = tight ? d[pos] : 9; // tight: cannot exceed the limit's digit
int total = 0;
for (int x = 0; x <= limit; x++) {
if (x == 7) continue; // forbidden digit
total += go(pos + 1, tight && x == limit);
}
memo.put(key, total);
return total;
}
// Count numbers from 1 to n that contain no digit 7, using digit DP.
static int countNoSeven(int n) {
String s = String.valueOf(n);
d = new int[s.length()];
for (int i = 0; i < d.length; i++) d[i] = s.charAt(i) - '0';
memo.clear();
return go(0, true) - 1; // remove the number 0
}
public static void main(String[] args) {
int fast = countNoSeven(235);
int slow = 0;
for (int i = 1; i <= 235; i++) if (!String.valueOf(i).contains("7")) slow++;
System.out.println(fast + " " + slow); // 194 194
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// countNoSeven counts numbers from 1 to n that contain no digit 7, using digit DP.
func countNoSeven(n int) int {
s := strconv.Itoa(n)
d := make([]int, len(s)) // digits of the limit
for i, ch := range s {
d[i] = int(ch - '0')
}
memo := map[int]int{}
var count func(pos int, tight bool) int
count = func(pos int, tight bool) int {
if pos == len(d) {
return 1 // built one valid number (maybe 0)
}
key := pos * 2
if tight {
key++
}
if v, ok := memo[key]; ok {
return v
}
limit := 9
if tight {
limit = d[pos] // tight: cannot exceed the limit's digit
}
total := 0
for x := 0; x <= limit; x++ {
if x == 7 { // forbidden digit
continue
}
total += count(pos+1, tight && x == limit)
}
memo[key] = total
return total
}
return count(0, true) - 1 // remove the number 0
}
func main() {
fast := countNoSeven(235)
slow := 0
for i := 1; i <= 235; i++ {
if !strings.Contains(strconv.Itoa(i), "7") {
slow++
}
}
fmt.Println(fast, slow) // 194 194
}Time: O(digits × 10 × states) · Extra space: O(digits × states). Only about 2 × (number of digits) states exist here, so even a 18-digit limit takes a few hundred steps.
Watch out for
- Forgetting that the limit itself is allowed; the "tight" path that follows its digits must be counted.
- Counting the number 0 (all zeros) by accident, or counting leading zeros as real digits when the rule is about digits.
- Caching without the tight flag in the key. Tight and free states give different answers.
Quick check
- What does "tight" mean?
- All digits so far equal the limit's digits
- The number is small
- We have used the digit 7
- After placing a digit smaller than the limit's digit, the rest...
- Must copy the limit
- Is free: any allowed digit
- Must be zeros
- With 3 free slots and 9 allowed digits, how many fillings?
- 27
- 729
- 999