#2521
Distinct Prime Factors of Product of Array
MediumArrayHash TableMathNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * sqrt(m)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * sqrt(m))Space O(n)
Instead of calculating the product, we can directly find the prime factors of each number in the array. This way, we avoid overflow and only focus on the distinct prime factors.
⚙️
Algorithm
4 steps- 1Step 1: Create a set to store distinct prime factors.
- 2Step 2: For each number in the array, find its prime factors.
- 3Step 3: Add each prime factor to the set.
- 4Step 4: Return the size of the set as the count of distinct prime factors.
solution.py18 lines
1# Full working Python code
2from math import isqrt
3
4def prime_factors(n):
5 factors = set()
6 for i in range(2, isqrt(n) + 1):
7 while n % i == 0:
8 factors.add(i)
9 n //= i
10 if n > 1:
11 factors.add(n)
12 return factors
13
14def distinct_prime_factors(nums):
15 primes = set()
16 for num in nums:
17 primes.update(prime_factors(num))
18 return len(primes)ℹ
Complexity note: The time complexity is O(n * sqrt(m)) where n is the number of elements in nums and m is the maximum value in nums. This is because we find prime factors for each number, and the space complexity is O(n) due to the storage of distinct primes.
- 1Calculating the product directly can lead to overflow; focus on prime factors instead.
- 2Using a set helps in automatically handling duplicates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.