Count the Number of Square-Free Subsets - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,4,5]
Output: 3
💡 Note: Square-free subsets are [3], [4], [5]. Note that [4,4] has product 16 = 4², so it's not square-free. [3,4], [3,5], [4,5] would work but [3,4,4] and others with 4,4 don't.
Example 2 — All Valid
$ Input: nums = [1]
Output: 1
💡 Note: Only subset is [1], and 1 is square-free (no square factors other than 1).
Example 3 — Prime Numbers
$ Input: nums = [2,3,5]
Output: 7
💡 Note: All 7 non-empty subsets work: [2], [3], [5], [2,3], [2,5], [3,5], [2,3,5]. Products are 2,3,5,6,10,15,30 - all square-free.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Count Square-Free Subsets INPUT nums array: 3 idx 0 4 idx 1 4 idx 2 5 idx 3 Square-Free Definition: Not divisible by any perfect square > 1 Examples: 6 = 2*3 (OK) 12 = 4*3 (NO - has 4) Primes <= 30: {2,3,5,7,11,13,17,19,23,29} 10 primes = 10 bits bitmask ALGORITHM STEPS 1 Filter Square-Free Skip 4 (has factor 4=2^2) Valid: [3, 5] 2 Create Prime Masks 3 = prime[1] = mask 0010 5 = prime[2] = mask 0100 3 DP with Bitmask dp[mask] = count of subsets with prime mask = mask DP Transitions: dp[0] = 1 (empty) Add 3: dp[0010] += dp[0] Add 5: dp[0100] += dp[0] 4 Sum All States Answer = sum(dp) - 1 (subtract empty subset) FINAL RESULT Square-Free Subsets: 1. {3} Product = 3 (OK) 2. {5} Product = 5 (OK) 3. {3, 5} Product = 15 (OK) Excluded: {4}, {4,4} - contain 4=2^2 OUTPUT 3 Key Insight: Use bitmask DP where each bit represents a prime factor. A number is square-free if each prime appears at most once. Track which primes are used in each subset to ensure no prime is repeated. Time: O(n * 2^10) since we only need 10 primes for numbers up to 30. Space: O(2^10). TutorialsPoint - Count the Number of Square-Free Subsets | Bitmask DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~35 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen