LeetCode solutions

1057. Numbers With Repeated Digits

My accepted Python solution to LeetCode problem 1057, Numbers With Repeated Digits, running in 0ms.

  • Difficulty: Hard
  • Python
  • Runtime 0ms
  • Memory 17.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.4MB, accepted 2026-01-01.

python
class Solution:
    def numDupDigitsAtMostN(self, n: int) -> int:
        # Count numbers WITHOUT repeated digits, then subtract from n
        # Total with repeated = n - numbers without repeated
        
        def count_no_repeat(n):
            if n < 0:
                return 0
            s = str(n)
            length = len(s)
            
            # Count numbers with fewer digits
            result = 0
            for i in range(1, length):
                # First digit: 9 choices (1-9)
                # Remaining: permutation of remaining digits
                result += 9 * perm(9, i - 1)
            
            # Count numbers with same number of digits
            used = set()
            for i, c in enumerate(s):
                d = int(c)
                # Count numbers where digit at position i is less than d
                for x in range(0 if i > 0 else 1, d):
                    if x not in used:
                        result += perm(10 - i - 1, length - i - 1)
                
                if d in used:
                    break
                used.add(d)
            else:
                # n itself has no repeated digits
                result += 1
            
            return result
        
        def perm(n, k):
            if k > n:
                return 0
            result = 1
            for i in range(k):
                result *= (n - i)
            return result
        
        return n - count_no_repeat(n)

Source