The Number of Good Subsets

You're given an integer array nums. Your task is to find all good subsets - subsets whose product can be represented as a product of distinct prime numbers.

What makes a subset "good"?
A subset is good if its product contains each prime factor at most once. In other words, no prime number appears more than once in the prime factorization.

Examples:
• Product = 6 = 2 × 3 ✅ (distinct primes)
• Product = 12 = 2² × 3 ❌ (prime 2 appears twice)
• Product = 30 = 2 × 3 × 5 ✅ (all distinct primes)

Special case: The number 1 can be included in any subset without affecting whether it's good or not.

Return the count of all different good subsets modulo 109 + 7.

Input & Output

example_1.py — Basic Good Subsets
$ Input: nums = [1,2,3,4]
Output: 6
💡 Note: Good subsets are: [2], [3], [2,3], [1,2], [1,3], [1,2,3]. Each has a product with distinct prime factors. [4] and [1,4] are not good since 4 = 2×2 has repeated prime factor 2.
example_2.py — All Ones
$ Input: nums = [4,2,3,15]
Output: 5
💡 Note: Good subsets are: [2], [3], [15], [2,3], [15] where 15 = 3×5. Note that [4] is invalid due to repeated prime factor 2.
example_3.py — With Ones
$ Input: nums = [1,1,2]
Output: 7
💡 Note: Good subsets: [2], [1,2], [1,2] (second occurrence), [1,1,2], [1], [1], [1,1]. The 1s can be combined freely with any other good subset.

Visualization

Tap to expand
2357Good Combo[2,3] = 6Bad Combo[4] = 2×2DP Statemask: 10111Special GuestPrime Orchestra Performance🎵 Each prime plays exactly once per song 🎵
Understanding the Visualization
1
Audition Phase
Count available musicians and reject those who would play the same note twice (numbers with repeated prime factors)
2
Ensemble Planning
Create a seating chart (bitmask) showing which notes are being played in each arrangement
3
Performance Counting
Use dynamic programming to count all valid arrangements where no note is repeated
4
Special Guests
Add the versatile musicians (1s) who can join any performance without changing the harmony
Key Takeaway
🎯 Key Insight: By using bitmask DP with only 10 relevant primes, we reduce the problem from exponential subset enumeration to polynomial state transitions, achieving optimal efficiency while handling the special case of 1s elegantly.

Time & Space Complexity

Time Complexity
⏱️
O(n + 2^p × k)

O(n) to count frequencies, O(2^p × k) for DP where p=10 primes and k≤10 distinct valid numbers

n
2n
Linear Growth
Space Complexity
O(2^p)

DP array of size 2^10 = 1024 to store states for all prime combinations

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 30
  • All numbers in nums are in range [1, 30]
  • Answer should be returned modulo 109 + 7
Asked in
Google 15 Amazon 8 Meta 12 Microsoft 6
26.4K 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