Skip to content
Problem 357 · LeetCode 357(opens in a new tab)

Count Numbers with Unique Digits

MediumBacktracking

Given an integer n, count the numbers x with 0 ≤ x < 10^n whose digits are all different from each other.

For example, 307 counts but 330 does not, because its 3 appears twice. The number 0 counts as well.

Example 1

Input:  n = 3
Output: 739
Why:    1 (zero) + 9 one-digit + 81 two-digit + 648 three-digit
2 more examples and the constraints

Example 2

Input:  n = 0
Output: 1
Why:    only x = 0 is below 10^0 = 1

Example 3

Input:  n = 1
Output: 10
Why:    0 to 9 all have a single digit

Constraints

  • 0 ≤ n ≤ 8

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count by length with a productO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 8Verdict
Build every valid numberO(answer)
Passes; 2.3 million numbers built
Count by length with a productO(n)
Best; 8 steps

n = the number of digits; answer = the count returned.

Edge cases to test

  • n = 0. Only 0 is below 1, so the answer is 1.
  • n = 1. All ten one-digit numbers count, 0 included: 10.
  • Leading zeros. Write 7 as 7, not 007: the first digit of a longer number has 9 choices, not 10.
  • The largest n. n = 8 gives 2,345,851; it fits easily in an int.

Common mistakes

  • Giving the first digit 10 choices, which counts numbers like 012 as three digits.
  • Forgetting to add 1 for the number 0.
  • Brute-forcing every x below 10^n, which is 100 million checks for n = 8.

How to talk through it

  1. 1Clarify. Does 0 count? Is the range 0 ≤ x < 10^n, so n digits at most?
  2. 2Give the search. Build numbers digit by digit with a used-digit mask and count them.
  3. 3Count by length. A k-digit number has 9 first-digit choices, then 9, 8, 7, ... for the rest.
  4. 4Code the loop. Keep a running product, add it for each length, and start the total at 1.
  5. 5Test out loud. Check n = 0 gives 1, n = 1 gives 10 and n = 3 gives 739.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?