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
Good Subsets with Bitmask DP INPUT Integer Array nums[] 1 [0] 2 [1] 3 [2] 4 [3] First 10 Primes (Bitmask): 2,3,5,7,11,13,17,19,23,29 Valid Numbers (no p^2): 1: special (multiplier) 2: prime (mask=0001) 3: prime (mask=0010) 4 = 2x2 (INVALID - p^2) ALGORITHM STEPS 1 Count Valid Numbers Filter nums with no p^2 2 Create Prime Bitmask Map each num to prime bits 3 DP Transition dp[mask|m] += dp[mask]*cnt 4 Multiply by 1s count Result * 2^(count of 1s) DP State Table (mask) mask primes dp 0000 {} 1 0001 {2} 1 0010 {3} 1 0011 {2,3} 1 Sum of dp[mask>0] = 3 FINAL RESULT All Good Subsets: 1. {2} prod=2 OK 2. {3} prod=3 OK 3. {2,3} prod=6 OK 4. {1,2} prod=2 OK 5. {1,3} prod=3 OK 6. {1,2,3} prod=6 OK Note: {4} invalid (4=2^2) {1} alone not counted OUTPUT 6 3 base * 2^1 (one 1) = 6 Key Insight: Use bitmask DP where each bit represents a prime. A number is valid only if it has no prime squared factors. Track which prime combinations are achievable. Numbers with value 1 can be added to any valid subset (multiply final count by 2^count_of_ones). Time: O(n * 2^10) TutorialsPoint - The Number of Good Subsets | Dynamic Programming with Bitmask
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