Count Numbers with Unique Digits

MediumMath · Combinatorics (Digit Counting)🧩 Digit DPLeetCode #357 ↗Updated

Problem

Given n, count the integers x with 0 ≤ x < 10n whose decimal digits are all different (e.g. 907 counts, 404 does not).
Inputn=2Output91 (all of 0..99 except 11,22,...,99)
Inputn=0Output1 (only 0)
Inputn=3Output739

0 ≤ n ≤ 8

Try it yourself

Java
class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Count by length. A k-digit number (k ≥ 2) has 9 choices for the leading digit (no 0), then 9, 8, 7, … for the rest, so count(k) = 9 · 9 · 8 ·…· (11-k); add the 10 one-digit numbers.
PatternDigit DP

Instinct Count numbers in [L, R] (R up to 10^9 or 10^18) whose digits obey a rule - build the number digit by digit with a "still tight to N" flag.

Memory hack Walk the digits on a leash - stay tight to N or break free, and once free you never go back. Remember PTLS - Position, Tight, Leading zero, State.

Open the Digit DP guide →

Approaches

Brute ForceCheck Every Number

Time O(10n · n)Space O(1)

Loop over every x below 10n and peel its digits with % 10, using a 10-bit mask to detect a repeat.

Java
public int countNumbersWithUniqueDigits(int n) {
    int limit = 1;
    for (int i = 0; i < n; i++) limit *= 10;
    int count = 0;
    for (int x = 0; x < limit; x++)
        if (allDistinct(x)) count++;
    return count;
}

private boolean allDistinct(int x) {
    int seen = 0; // bit d set = digit d already used
    do {
        int d = x % 10;
        if ((seen >> d & 1) == 1) return false;
        seen |= 1 << d;
        x /= 10;
    } while (x > 0);
    return true;
}

Trivially right, but 108 numbers at n = 8 is painfully slow.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every NumberO(10n · n)O(1)
BetterBacktracking: Build Only Valid NumbersO(answer)O(n)
OptimalProduct Rule per LengthO(n)O(1)
Common pitfalls
  • Allowing 0 as the leading digit — that double-counts shorter numbers.
  • Forgetting the number 0 itself (answer for n = 0 is 1, not 0).
  • Letting the product run past 10 digits; it must become 0 (pigeonhole).
Interview tips
  • Start with brute force to confirm small answers (n = 2 → 91).
  • Explain the leading-digit choice (9) vs later choices (9, 8, 7, …).
  • Mention this is the warm-up for digit DP problems with an upper bound (e.g. 1012).
Pattern
Combinatorial counting by length → counting numbers below a power of 10 with a digit-level rule.
My notes saved in this browser