<p>We call a positive integer <strong>special</strong> if all of its digits are <strong>distinct</strong>.</p>

<p>Given a <strong>positive</strong> integer <code>n</code>, return <em>the number of special integers that belong to the interval </em><code>[1, n]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 20
<strong>Output:</strong> 19
<strong>Explanation:</strong> All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 5
<strong>Output:</strong> 5
<strong>Explanation:</strong> All the integers from 1 to 5 are special.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> n = 135
<strong>Output:</strong> 110
<strong>Explanation:</strong> There are 110 integers from 1 to 135 that are special.
Some of the integers that are not special are: 22, 114, and 131.</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>9</sup></code></li>
</ul>

class Solution:
    def countSpecialNumbers(self, n: int) -> int:
        def countSpecialNumbersWithDigits(d):
            # Count numbers with exactly d digits that are special
            count = 0
            for i in range(1, d + 1):
                count += 9 * self.permute(9, i - 1)
            return count
        
        def countUpToPrefix(prefix, length):
            # Count numbers that start with a given prefix and have the required length
            used = set(str(prefix))
            if len(used) != len(str(prefix)):
                return 0
            count = 0
            for i in range(len(str(prefix)), length):
                for j in range(10):
                    if j == 0 and i == 0:
                        continue
                    if str(j) in used:
                        continue
                    count += self.permute(10 - i - 1, length - i - 1)
                used.add(str(prefix)[i])
            return count
        
        def permute(n, k):
            # Permutation nPk
            result = 1
            for i in range(k):
                result *= (n - i)
            return result
        
        num_str = str(n)
        num_digits = len(num_str)
        total_count = countSpecialNumbersWithDigits(num_digits - 1)
        
        used_digits = set()
        for i, digit in enumerate(num_str):
            for d in range(1 if i == 0 else 0, int(digit)):
                if str(d) not in used_digits:
                    total_count += permute(10 - (i + 1), num_digits - (i + 1))
            if digit in used_digits:
                break
            used_digits.add(digit)
        else:
            total_count += 1
        
        return total_count
    
    def permute(self, n, k):
        result = 1
        for i in range(k):
            result *= (n - i)
        return result
39