#2572

Count the Number of Square-Free Subsets

Medium
ArrayMathDynamic ProgrammingBit ManipulationNumber TheoryBitmaskBit ManipulationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k), where k is the number of unique primes up to 30.
Space
O(1)
O(n)
💡

Intuition

Time O(n * k), where k is the number of unique primes up to 30.Space O(n)

The optimal solution uses bit manipulation and dynamic programming to efficiently count square-free subsets. By tracking prime factors and their occurrences, we can avoid recalculating products for each subset.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute the prime numbers up to a certain limit (e.g., 30) and their corresponding masks.
  2. 2Step 2: For each number in nums, calculate its prime factorization and create a bitmask representing the primes involved.
  3. 3Step 3: Use a dynamic programming approach to count subsets while ensuring that no prime factor appears more than once.
solution.py31 lines
1# Full working Python code
2from collections import defaultdict
3
4MOD = 10**9 + 7
5
6def prime_factors_mask(num):
7    mask = 0
8    for i in range(2, 31):
9        if num % i == 0:
10            count = 0
11            while num % i == 0:
12                num //= i
13                count += 1
14            if count > 1:
15                return -1  # Not square-free
16            mask |= (1 << (i - 2))  # Set the bit for prime i
17    return mask
18
19def count_square_free_subsets(nums):
20    n = len(nums)
21    dp = defaultdict(int)
22    dp[0] = 1  # Empty subset
23    for num in nums:
24        mask = prime_factors_mask(num)
25        if mask == -1:
26            continue
27        for m in list(dp.keys()):
28            if m & mask == 0:  # No common prime factors
29                dp[m | mask] = (dp[m | mask] + dp[m]) % MOD
30    return (sum(dp.values()) - 1) % MOD  # Exclude the empty subset
31

Complexity note: This complexity is efficient because we avoid recalculating products and only track unique prime factors, significantly reducing the number of checks needed.

  • 1Understanding square-free integers is crucial.
  • 2Efficiently managing prime factors can reduce complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.