<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 count_permutations(m, k):
            """ Helper function to count permutations of k digits from m choices """
            if k > m:
                return 0
            result = 1
            for i in range(k):
                result *= (m - i)
            return result
        
        digits = list(map(int, str(n)))
        num_digits = len(digits)
        
        # Count special numbers with fewer digits than n
        count = 0
        for d in range(1, num_digits):
            count += 9 * count_permutations(9, d - 1)
        
        # Count special numbers with the same number of digits as n
        seen = set()
        for i, x in enumerate(digits):
            for y in range(1 if i == 0 else 0, x):
                if y in seen:
                    continue
                count += count_permutations(9 - i, num_digits - i - 1)
            if x in seen:
                break
            seen.add(x)
        else:
            count += 1  # count n itself if it's special
        
        return count

# Example usage:
solution = Solution()
print(solution.countSpecialNumbers(20))  # Output: 19
print(solution.countSpecialNumbers(5))   # Output: 5
print(solution.countSpecialNumbers(135)) # Output: 110
35