#1012

Numbers With Repeated Digits

Hard
MathDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(d²)
Space
O(1)
O(d)
💡

Intuition

Time O(d²)Space O(d)

Instead of counting numbers with repeated digits directly, we can count the numbers without repeated digits and subtract from n. This is more efficient as it avoids checking each number individually.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the total numbers with unique digits up to the number of digits in n.
  2. 2Step 2: For each digit position, calculate how many unique digit numbers can be formed.
  3. 3Step 3: Handle the case where the number has the same prefix as n.
  4. 4Step 4: Subtract the count of unique digit numbers from n to get the count of numbers with repeated digits.
solution.py17 lines
1def countDupDigits(n):
2    str_n = str(n)
3    length = len(str_n)
4    count = 0
5    for i in range(1, length):
6        count += 9 * (10 ** (i - 1)) * (9 ** (i - 1))
7    used = set()
8    for i in range(length):
9        for j in range(1 if i == 0 else 0, int(str_n[i])):
10            if j not in used:
11                count += (9 - i) * (9 ** (length - i - 1))
12        if str_n[i] in used:
13            break
14        used.add(str_n[i])
15    return n - count
16
17print(countDupDigits(20)

Complexity note: The time complexity is O(d²) where d is the number of digits in n. This is because we iterate over the digits and for each digit, we may check against previously used digits.

  • 1Counting unique digits is more efficient than checking each number individually.
  • 2Using sets helps track used digits effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.