#357

Count Numbers with Unique Digits

Medium
MathDynamic ProgrammingBacktrackingBacktrackingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all numbers, we can calculate how many unique digit numbers exist based on the number of digits. This is much faster and avoids unnecessary checks.

⚙️

Algorithm

5 steps
  1. 1Step 1: If n is 0, return 1 (only the number 0).
  2. 2Step 2: Initialize count with 10 (for numbers 0-9).
  3. 3Step 3: For each digit from 1 to n-1, calculate the number of unique combinations.
  4. 4Step 4: Use a decreasing factor for available digits (9 for the first digit, then 9, 8, etc.).
  5. 5Step 5: Accumulate the count for each digit length.
solution.py13 lines
1# Full working Python code
2
3def countNumbersWithUniqueDigits(n):
4    if n == 0:
5        return 1
6    count = 10
7    uniqueDigits = 9
8    availableDigits = 9
9    for i in range(1, n):
10        count += uniqueDigits * availableDigits
11        uniqueDigits *= availableDigits
12        availableDigits -= 1
13    return count

Complexity note: The time complexity is O(n) because we only loop through the number of digits, which is at most 8 (since n <= 8).

  • 1Unique digit numbers can be calculated based on the number of digits rather than generating each number.
  • 2The first digit has 9 options (1-9), and subsequent digits have decreasing options based on what has already been used.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.