The Count the Number of Square-Free Subsets interview question asks you to find the number of non-empty subsets of an array such that the product of elements in the subset is a "square-free" integer. A number is square-free if no prime factor appears more than once in its prime factorization (i.e., it is not divisible by any square ).
For example, 6 () is square-free, but 12 () is not.
This "Medium/Hard" problem from Media.net and Google tests bitmask dynamic programming and number theory. Since the elements are typically small (), there are only a few primes to consider. It evaluations whether a candidate can represent the prime factorization of a number as a bitmask and use DP to ensure no two numbers in a subset share a prime factor.
The problem is solved using Bitmask DP.
dp[mask] is the number of subsets whose product has prime factors represented by mask.num_mask, update dp[new_mask | num_mask] += dp[new_mask] for all new_mask that don't overlap with num_mask.nums = [2, 3, 6]
01, 3 is mask 10, 6 is mask 11.dp[00] = 1 (empty).dp[01] = 1.dp[10] += dp[00] (Sub {3})dp[11] += dp[01] (Sub {2, 3})dp[11] already has factors 2 and 3. Cannot add 6 to any mask except 00.dp[11] += dp[00] (Sub {6})
Total subsets = . ({2}, {3}, {2,3}, {6}).Whenever a problem involves "product property X" and the numbers are small, think about prime factor bitmasks. A bitmask of length 10 is very manageable for DP.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| The Number of Good Subsets | Hard | Solve | |
| Number of Ways to Build Sturdy Brick Wall | Medium | Solve | |
| Find Sum of Array Product of Magical Sequences | Hard | Solve | |
| Minimum XOR Sum of Two Arrays | Hard | Solve | |
| Split Array With Same Average | Hard | Solve |