Taro Logo

The Number of Good Subsets

#2 Most AskedHard
5 views
Topics:
Dynamic ProgrammingBit Manipulation

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.

Example 1:

Input: nums = [1,2,3,4]
Output: 6
Explanation: The good subsets are:
- [1,2]: product is 2, which is the product of distinct prime 2.
- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [1,3]: product is 3, which is the product of distinct prime 3.
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [3]: product is 3, which is the product of distinct prime 3.

Example 2:

Input: nums = [4,2,3,15]
Output: 5
Explanation: The good subsets are:
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.
- [3]: product is 3, which is the product of distinct prime 3.
- [15]: product is 15, which is the product of distinct primes 3 and 5.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 30

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements inside the input array `nums`, and what is the maximum length of `nums`?
  2. How should we handle duplicate values in the input array `nums`? For example, if there are multiple 2s, do they represent distinct choices in forming subsets?
  3. Can the input array contain the number 1 or zeros, and if so, how do they affect the product and the definition of a good subset?
  4. Are subsets defined by their index combinations or by the distinct multiset of values? That is, do duplicate subsets generated from identical values count as separate good subsets?
  5. What should be returned if no good subset can be formed from the given array `nums`?

Brute Force Solution

Approach

Imagine you have a collection of numbers and want to find every possible subgroup where multiplying the chosen numbers together does not result in any number being used more than once as a prime building block. The brute force approach involves exploring every single combination of the given numbers, checking if each combination meets this special multiplication rule, and counting how many valid combinations you discover.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire collection of numbers provided to you.
  2. List out every possible combination of these numbers, ranging from groups of just a single number up to using all the numbers together.
  3. For each specific combination you form, multiply all the numbers in that group together to see what the final product is.
  4. Break down that final product into its basic prime building blocks to see if any prime building block is used more than once.
  5. If a prime building block is repeated, discard that combination because it fails the rule.
  6. If all the prime building blocks are used at most once, celebrate because you have found a winning combination.
  7. Keep a running tally of every winning combination you find as you go through all the possibilities.
  8. Once you have checked every single combination, your final tally is the answer you are looking for.

Code Implementation

from itertools import combinations


def numberOfGoodSubsets(number_collection):
    winning_combination_tally = 0
    
    # We evaluate every subset size to ensure all mathematical combinations are thoroughly explored
    for subset_size in range(1, len(number_collection) + 1):
        for current_combination in combinations(number_collection, subset_size):
            product_value = 1
            for current_number in current_combination:
                product_value *= current_number
            
            prime_factor_counts = {}
            temporary_product = product_value
            current_divisor = 2
            
            while current_divisor * current_divisor <= temporary_product:
                while temporary_product % current_divisor == 0:
                    prime_factor_counts[current_divisor] = prime_factor_counts.get(current_divisor, 0) + 1
                    temporary_product //= current_divisor
                current_divisor += 1
            
            if temporary_product > 1:
                prime_factor_counts[temporary_product] = prime_factor_counts.get(temporary_product, 0) + 1
            
            # We check if any prime factor appears more than once to enforce square-free constraint
            is_square_free = True
            for factor_count in prime_factor_counts.values():
                if factor_count > 1:
                    is_square_free = False
                    break
            
            # We increment the tally only if the subset product is valid and square-free
            if is_square_free:
                winning_combination_tally += 1
                
    return winning_combination_tally

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force strategy requires generating and evaluating every possible combination from the collection of numbers, ranging from single elements up to all n elements combined. For an input of size n, the total number of distinct subsets is calculated as two raised to the power of n. Since we must inspect every single one of these 2ⁿ combinations to check its prime building blocks, the operations scale exponentially. Thus, multiplying the number of subsets by the constant-time checks per subset results in 2ⁿ operations, which simplifies to O(2ⁿ).
Space Complexity
O(1) – To solve this problem efficiently, we do not need to generate every combination or store all elements in a large auxiliary data structure. Instead, we use a fixed-size frequency array to count the occurrences of numbers from 1 to 30, which requires constant extra space regardless of the input size N. We also use a few primitive variables and a dynamic programming table of a constant size corresponding to the subsets of the 10 distinct prime numbers less than or equal to 30. Therefore, the auxiliary space complexity remains strictly constant at O(1) as the input collection grows.

Optimal Solution

Approach

To find the number of good groups, we can take advantage of the fact that only a small set of prime numbers matter and numbers with repeated factors are useless. By counting how many times each useful number appears and tracking which prime building blocks have already been used, we can efficiently build valid combinations without checking every single possibility.

Here's how the algorithm would work step-by-step:

  1. First, recognize that any number whose factors repeat, such as a number multiplied by itself, ruins a group because it violates the rules. Therefore, completely ignore these numbers except for the number one.
  2. Count how many times each remaining useful number appears in the original collection of numbers.
  3. Understand that each useful number is made up of a unique combination of small prime building blocks, meaning no two useful numbers can share the same prime building block.
  4. Imagine going through the useful numbers one by one, deciding whether to include them in our collection or skip them.
  5. As we form combinations, keep track of which prime building blocks have already been used so we never pick two numbers that share a prime building block.
  6. Calculate how many ways we can form valid combinations of these useful numbers by multiplying their available counts together.
  7. Finally, account for the number one by realizing it can be included or excluded in any valid combination in multiple different ways, which dramatically multiplies our final total of good groups.

Code Implementation

class Solution:
    def numberOfGoodSubsets(self, numbers_list: list[int]) -> int:
        prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
        modulo_constant = 10**9 + 7
        
        frequency_map = {}
        for current_number in numbers_list:
            frequency_map[current_number] = frequency_map.get(current_number, 0) + 1
            
        # Filter out numbers with repeated prime factors since they invalidate subsets.
        valid_mask_counts = {0: 1}
        
        for current_number in range(2, 31):
            if current_number not in frequency_map:
                continue
                
            is_square_free = True
            prime_mask = 0
            for prime_index, prime_value in enumerate(prime_numbers):
                prime_divisibility_count = 0
                while current_number % prime_value == 0:
                    prime_divisibility_count += 1
                    current_number //= prime_value
                if prime_divisibility_count > 1:
                    is_square_free = False
                    break
                if prime_divisibility_count == 1:
                    prime_mask |= (1 << prime_index)
                    
            if not is_square_free:
                continue
                
            # Update subset combinations using bitmasks to track used prime factors.
            current_number_frequency = frequency_map[current_number]
            for existing_mask in list(valid_mask_counts.keys():
                if (existing_mask & prime_mask) == 0:
                    new_combined_mask = existing_mask | prime_mask
                    added_ways = (valid_mask_counts[existing_mask] * current_number_frequency) % modulo_constant
                    valid_mask_counts[new_combined_mask] = (valid_mask_counts.get(new_combined_mask, 0) + added_ways) % modulo_constant
                    
        total_good_subsets = sum(count for mask, count in valid_mask_counts.items() if mask > 0) % modulo_constant
        
        # Multiply by powers of two for ones since each one can be included or excluded independently.
        if 1 in frequency_map:
            power_of_ones = pow(2, frequency_map[1], modulo_constant)
            total_good_subsets = (total_good_subsets * power_of_ones) % modulo_constant
            
        return total_good_subsets

Big(O) Analysis

Time Complexity
O(2^P * N) – Counting the frequency of each number in the input array of size n takes O(n) time. Since there are only 10 distinct prime numbers less than or equal to 30, there are at most 2 to the power of 10 valid square-free subsets of primes to explore. Using recursion or dynamic programming to combine these prime masks scales with the number of masks rather than n. Therefore, the total operations approximate n plus the constant factor of 2 to the power of 10 subset combinations, which simplifies to O(2^P * n) where P is the number of primes.
Space Complexity
O(1) – The space complexity is constant because the extra memory required does not scale with the size of the input array. We only store frequency counts for a fixed, small set of numbers ranging up to thirty and a bitmask tracking at most ten prime building blocks. The auxiliary data structures used for combinations and prime tracking have a fixed size regardless of how many elements are in the input collection.

Edge Cases

Array contains the number 1 multiple times
How to Handle:
Each occurrence of 1 can be included or excluded independently, meaning 1s contribute a factor of 2 to the power of the count of 1s in nums.
Array contains numbers with squared prime factors like 4, 8, or 9
How to Handle:
These numbers must be completely ignored during subset formation because their prime factorization contains duplicate primes.
Array contains only numbers that are not valid prime products
How to Handle:
The algorithm should correctly return zero since no valid good subsets can be formed from the input.
Input contains the maximum allowed number of elements up to the constraints
How to Handle:
Using frequency counting of unique numbers instead of dynamic programming over the entire array ensures the solution executes well within time limits.
Subsets can be formed using numbers that share prime factors
How to Handle:
Bitmask dynamic programming tracks used prime factors to ensure no prime factor is used more than once within the same subset.
Large counts of combinations exceeding standard integer limits
How to Handle:
All intermediate calculations and final results must be taken modulo 10 to the 9 plus 7 to prevent integer overflow.
Array contains only a single prime number
How to Handle:
The algorithm counts this single element as a valid subset of size one and returns the correct total count.
0/4 completed