#3747

Count Distinct Integers After Removing Zeros

Medium
MathDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(log n)Space O(1)

Instead of iterating through all numbers, we can count the distinct integers formed by digits 1-9, avoiding zeros altogether. This is efficient and leverages combinatorial counting.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of digits in n.
  2. 2Step 2: For each digit position, calculate combinations of digits (1-9) that can be formed without zeros.
  3. 3Step 3: Sum the counts of valid numbers formed for all digit lengths up to the length of n.
solution.py10 lines
1def countDistinctIntegers(n):
2    count = 0
3    str_n = str(n)
4    length = len(str_n)
5    for i in range(1, length):
6        count += 9 * (10 ** (i - 1))
7    for i in range(1, int(str_n[0]) + 1):
8        if i > 1:
9            count += 10 ** (length - 1) - 10 ** (length - 2)
10    return count

Complexity note: This approach runs in O(log n) because we only process the digits of n, making it efficient for large values.

  • 1Removing zeros simplifies the problem to counting valid digit combinations.
  • 2Understanding digit positions helps in optimizing the counting process.

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