Distinct Prime Factors of Product of Array - Problem

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 1 is called prime if it is divisible by only 1 and itself.
  • An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,3,6]
Output: 2
💡 Note: Product = 2×4×3×6 = 144 = 2⁴×3². The distinct prime factors are 2 and 3, so return 2.
Example 2 — Single Element
$ Input: nums = [20]
Output: 2
💡 Note: 20 = 2²×5¹. The distinct prime factors are 2 and 5, so return 2.
Example 3 — Multiple Same Primes
$ Input: nums = [4,9,16]
Output: 2
💡 Note: Product = 4×9×16 = 576 = 2⁶×3². The distinct prime factors are 2 and 3, so return 2.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 2 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Distinct Prime Factors of Product of Array INPUT Array: nums 2 4 3 6 [0] [1] [2] [3] Product = 2 x 4 x 3 x 6 = 144 144 = 2^4 x 3^2 Prime factors: {2, 3} Count: 2 Input: nums = [2,4,3,6] ALGORITHM STEPS 1 Initialize Set Create empty set for primes 2 Process Each Number Factor each num individually Factorization: 2 --> {2} 4 = 2x2 --> {2} 3 --> {3} 6 = 2x3 --> {2, 3} Set: {2, 3} 3 Add to Set Duplicates auto-removed 4 Return Size Count distinct primes FINAL RESULT Distinct Prime Factors Found: 2 3 Both are prime numbers Verification: 144 / 2 = 72 [OK] 144 / 3 = 48 [OK] No other prime divides 144 Output: 2 Key Insight: Instead of computing the potentially huge product (which could overflow), we factor each number individually and collect all prime factors in a set. The set automatically handles duplicates, so we just return the set size. Time: O(n x sqrt(max_num)) | Space: O(distinct primes) TutorialsPoint - Distinct Prime Factors of Product of Array | Optimized - Factor Each Number Individually
Asked in
Google 15 Meta 12 Amazon 8
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen