MediumNo. 2572

Count the Number of Square-Free Subsets — LeetCode 2572 Python Solution

Topics
Bit Manipulation, Array, Math, Dynamic Programming, Bitmask
Reading time
4 min

The problem

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.

Example

Input
nums = [3,4,4,5]
Output
3
Explanation
There are 3 square-free subsets in this example:

Python solution

PythonSolution
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

Complexity

Time
O(n + C × M)
Space · auxiliary
O(M)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2572. Count the Number of Square-Free Subsets is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0805Split Array With Same AverageHard
1799Maximize Score After N OperationsHard
0464Can I WinMedium
0473Matchsticks to SquareMedium
0526Beautiful ArrangementMedium
0638Shopping OffersMedium

Frequently asked questions

How hard is LeetCode 2572. Count the Number of Square-Free Subsets?

LeetCode 2572. Count the Number of Square-Free Subsets is rated Medium on LeetCode.

What is the time complexity of LeetCode 2572. Count the Number of Square-Free Subsets?

The Python solution on this page runs in O(n + C × M).

What is the space complexity of LeetCode 2572. Count the Number of Square-Free Subsets?

The Python solution on this page uses O(M) auxiliary space.

What topics does LeetCode 2572. Count the Number of Square-Free Subsets cover?

LeetCode 2572. Count the Number of Square-Free Subsets is tagged Bit Manipulation, Array, Math, Dynamic Programming and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.