You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.

For example, if nums = [1, 2, 3, 4]:

  • [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.
  • [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.

Return the number of different good subsets in nums modulo 109 + 7.

A subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 6
💡 Note: Good subsets: [2], [3], [1,2], [1,3], [2,3], [1,2,3]. The subsets [4], [1,4], [2,4], [3,4], [1,2,4], [1,3,4], [2,3,4], [1,2,3,4] are not good because 4 = 2² contains repeated prime factor 2.
Example 2 — Only Prime Numbers
$ Input: nums = [2,3,5]
Output: 7
💡 Note: All non-empty subsets are good: [2], [3], [5], [2,3], [2,5], [3,5], [2,3,5]. Each contains only distinct prime factors.
Example 3 — Contains Invalid Numbers
$ Input: nums = [4,2,1]
Output: 3
💡 Note: Good subsets: [2], [1,2], [1]. Number 4 = 2² cannot be in any good subset due to repeated prime factor.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 30

Visualization

Tap to expand
The Number of Good SubsetsA good subset has product with distinct prime factors only1234SpecialPrimePrime2² = 2×2Good Subsets:[2] → 2 ✓[3] → 3 ✓[1,2] → 2 ✓[1,3] → 3 ✓[2,3] → 6 = 2×3 ✓[1,2,3] → 6 = 2×3 ✓Bad Subsets:[4] → 2² ✗[1,4] → 2² ✗Any with 4 ✗Total Good Subsets: 6
Understanding the Visualization
1
Input Array
Given array [1,2,3,4] with mixed valid/invalid numbers
2
Prime Analysis
Check each number's prime factorization for uniqueness
3
Count Good Subsets
Return count of all valid combinations
Key Takeaway
🎯 Key Insight: Only numbers ≤ 30 with distinct prime factors can form good subsets, making bitmask DP highly efficient
Asked in
Meta 3 Google 2
28.0K Views
Medium Frequency
~35 min Avg. Time
847 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