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 Array2436Input: nums = [2, 4, 3, 6]2 → {2}4 → {2}3 → {3}6 → {2,3}Prime: 2Prime: 3Output: 2 distinct prime factors
Understanding the Visualization
1
Input Array
Array of positive integers [2, 4, 3, 6]
2
Find Prime Factors
Factor each number: 2→{2}, 4→{2}, 3→{3}, 6→{2,3}
3
Count Unique
Union gives {2, 3}, so answer is 2
Key Takeaway
🎯 Key Insight: Factor each number individually to avoid overflow while collecting all unique prime factors
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