Count Special Integers — LeetCode 2376 Python Solution

HardMathDynamic Programming
Problem
#2376
Reading time
3 min

The problem

We call a positive integer special if all of its digits are distinct. Given a positive integer n, return the number of special integers that belong to the interval [1, n].

Example

Input
n = 20
Output
19
Explanation
All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.

Python solution

Python
class Solution:
    def countSpecialNumbers(self, n: int) -> int:
        @cache
        def dfs(i: int, mask: int, lead: bool, limit: bool) -> int:
            if i >= len(s):
                return int(lead ^ 1)
            up = int(s[i]) if limit else 9
            ans = 0
            for j in range(up + 1):
                if mask >> j & 1:
                    continue
                if lead and j == 0:
                    ans += dfs(i + 1, mask, True, limit and j == up)
                else:
                    ans += dfs(i + 1, mask | 1 << j, False, limit and j == up)
            return ans

        s = str(n)
        return dfs(0, 0, True, True)

Complexity

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

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2376. Count Special Integers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2376. Count Special Integers?
LeetCode 2376. Count Special Integers is rated Hard on LeetCode.
What is the time complexity of LeetCode 2376. Count Special Integers?
The Python solution on this page runs in O(m \times 2^D \times D).
What is the space complexity of LeetCode 2376. Count Special Integers?
The Python solution on this page uses O(m \times 2^D) auxiliary space.
What topics does LeetCode 2376. Count Special Integers cover?
LeetCode 2376. Count Special Integers is tagged Math and Dynamic Programming 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