Count the Number of Square-Free Subsets Problem
Description
LeetCode Problem 2572.
You are given a positive integer 0-indexed array nums.
A subset of the array nums is square-free if the product of its elements is a square-free integer.
A square-free integer is an integer that is divisible by no square number other than 1.
Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 10^9 + 7.
A non-empty subset of nums is an array that can be obtained by deleting some (possibly none but not all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [3,4,4,5]
Output: 3
Explanation: There are 3 square-free subsets in this example:
- The subset consisting of the 0^th element [3]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3^rd element [5]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0^th and 3^rd elements [3,5]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
Example 2:
Input: nums = [1]
Output: 1
Explanation: There is 1 square-free subset in this example:
- The subset consisting of the 0^th element [1]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 30
Solution
Approach: Bitmask Dynamic Programming
Every nums[i] is at most 30, so only the ten primes up to 29 matter. A subset is square-free when its product has no prime twice, so each prime may come from at most one chosen number. Numbers divisible by 4, 9 or 25 can never be chosen.
Let f[state] be the number of ways to choose numbers whose prime factors are exactly the set state. Start with f[0] = 2^cnt[1], since any number of 1s can be added. For each value x from 2 to 30 that occurs and is usable, with prime mask mask, go through states from large to small: if state contains mask, add cnt[x] * f[state ^ mask] to f[state]. The answer is the sum of all f minus 1 for the empty subset.
Complexity: time O(n + C * M), space O(M), where n is the length of nums, C = 30 and M = 2^10 is the number of masks.
from collections import Counter
class Solution:
def squareFreeSubsets(self, nums: List[int]) -> int:
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
cnt = Counter(nums)
mod = 10**9 + 7
n = len(primes)
f = [0] * (1 << n)
f[0] = pow(2, cnt[1])
for x in range(2, 31):
if cnt[x] == 0 or x % 4 == 0 or x % 9 == 0 or x % 25 == 0:
continue
mask = 0
for i, p in enumerate(primes):
if x % p == 0:
mask |= 1 << i
for state in range((1 << n) - 1, 0, -1):
if state & mask == mask:
f[state] = (f[state] + cnt[x] * f[state ^ mask]) % mod
return sum(v for v in f) % mod - 1