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: [3,4,4,5] → 334453 = 3¹4 = 2²4 = 2²5 = 5¹Square-freeSquare-freeSquare-freeSquare-free[3] ✓[4] ✓[5] ✓[4,4] ✗Product: 3Product: 4Product: 5Product: 16=4²[4,4] fails because 4×4=16=4², which has square factor 4²Result: 3 square-free subsets
Understanding the Visualization
1
Input Analysis
Array [3,4,4,5] with prime factors
2
Square-Free Check
Products must have no repeated prime factors
3
Count Result
Valid subsets: [3], [4], [5]
Key Takeaway
🎯 Key Insight: A subset is square-free if no prime factor appears with even total power across all elements
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