Distinct Prime Factors of Product of Array Problem
#2521
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2521.
Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums.
Note that:
- A number greater than
1is called prime if it is divisible by only1and itself. - An integer
val1is a factor of another integerval2ifval2 / val1is an integer.
Example 1:
Input: nums = [2,4,3,7,10,6]
Output: 4
Explanation:
The product of all the elements in nums is: 2 * 4 * 3 * 7 * 10 * 6 = 10080 = 2^5 * 3^2 * 5 * 7.
There are 4 distinct prime factors so we return 4.
Example 2:
Input: nums = [2,4,8,16]
Output: 1
Explanation:
The product of all the elements in nums is: 2 * 4 * 8 * 16 = 1024 = 2^10.
There is 1 distinct prime factor so we return 1.
Constraints:
1 <= nums.length <= 10^42 <= nums[i] <= 1000
Solution
Approach: Hash Set + Trial Division
The prime factors of the product are exactly the union of the prime factors of the individual numbers, so we never need to build the product.
Factorize each number by trial division up to its square root: whenever i divides n, add i to a set and divide it out completely. If something larger than 1 remains, it is itself a prime factor. The answer is the size of the set.
Complexity: O(n * sqrt(m)) time and O(m / log m) space for the set, where n is the array length and m the largest value.
class Solution:
def distinctPrimeFactors(self, nums: List[int]) -> int:
s = set()
for n in nums:
i = 2
while i <= n // i:
if n % i == 0:
s.add(i)
while n % i == 0:
n //= i
i += 1
if n > 1:
s.add(n)
return len(s)