Count Numbers with Unique Digits — LeetCode 357 Python Solution

MediumMathDynamic ProgrammingBacktracking
Problem
#357
Reading time
3 min

The problem

Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

Example

Input
n = 2
Output
91
Explanation
The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99

Python solution

Python
class Solution:
    def countNumbersWithUniqueDigits(self, n: int) -> int:
        @cache
        def dfs(i: int, mask: int, lead: bool) -> int:
            if i < 0:
                return 1
            ans = 0
            for j in range(10):
                if mask >> j & 1:
                    continue
                if lead and j == 0:
                    ans += dfs(i - 1, mask, True)
                else:
                    ans += dfs(i - 1, mask | 1 << j, False)
            return ans

        return dfs(n - 1, 0, True)

Complexity

MeasureComplexity
TimeO(n \times 2^D \times D)
SpaceO(n \times 2^D) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 357. Count Numbers with Unique Digits is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 357. Count Numbers with Unique Digits?
LeetCode 357. Count Numbers with Unique Digits is rated Medium on LeetCode.
What is the time complexity of LeetCode 357. Count Numbers with Unique Digits?
The Python solution on this page runs in O(n \times 2^D \times D).
What is the space complexity of LeetCode 357. Count Numbers with Unique Digits?
The Python solution on this page uses O(n \times 2^D) auxiliary space.
What topics does LeetCode 357. Count Numbers with Unique Digits cover?
LeetCode 357. Count Numbers with Unique Digits is tagged Math, Dynamic Programming and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview