LeetCode 2521: Distinct Prime Factors of Product of Array Solution

Master LeetCode problem 2521 (Distinct Prime Factors of Product of Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2521. Distinct Prime Factors of Product of Array

Problem Explanation

Explanation

To solve this problem, we need to calculate the product of all elements in the given array nums, find the prime factors of this product, and then count the distinct prime factors. We can achieve this by iterating over the elements in the array, calculating the product, finding the prime factors, and finally counting the distinct prime factors.

  1. Create a helper function to find all prime factors of a number.
  2. Calculate the product of all elements in the array.
  3. Find the prime factors of the product.
  4. Count the distinct prime factors found.

Time Complexity: O(n * sqrt(max_value)) where n is the number of elements in the array and max_value is the maximum value in the array. Space Complexity: O(sqrt(max_value)) for storing prime factors.

Solution Code

import java.util.*;

class Solution {
    public int distinctPrimeFactors(int[] nums) {
        Set<Integer> primeFactors = new HashSet<>();
        for (int num : nums) {
            for (int factor : findPrimeFactors(num)) {
                primeFactors.add(factor);
            }
        }
        return primeFactors.size();
    }

    private List<Integer> findPrimeFactors(int num) {
        List<Integer> factors = new ArrayList<>();
        for (int i = 2; i <= Math.sqrt(num); i++) {
            while (num % i == 0) {
                factors.add(i);
                num /= i;
            }
        }
        if (num > 1) {
            factors.add(num);
        }
        return factors;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2521 (Distinct Prime Factors of Product of Array)?

This page provides optimized solutions for LeetCode problem 2521 (Distinct Prime Factors of Product of Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2521 (Distinct Prime Factors of Product of Array)?

The time complexity for LeetCode 2521 (Distinct Prime Factors of Product of Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2521 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2521 in Java, C++, or Python.

Back to LeetCode Solutions