HardNo. 2376

Count Special Integers — LeetCode 2376 Python Solution

Topics
Math, Dynamic Programming
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

PythonSolution
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

Time
O(m × 2D × D)
Space · auxiliary
O(m × 2D)

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

Related problems
No.ProblemDifficulty
0062Unique PathsMedium
0070Climbing StairsEasy
0096Unique Binary Search TreesMedium
0233Number of Digit OneHard
0241Different Ways to Add ParenthesesMedium
0279Perfect SquaresMedium

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 × 2D × D).

What is the space complexity of LeetCode 2376. Count Special Integers?

The Python solution on this page uses O(m × 2D) 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.

Free to download. Check it runs on your machine, then pick a plan.