Count the Number of K-Free Subsets - Problem
You are given an integer array nums, which contains distinct elements and an integer k. A subset is called a k-Free subset if it contains no two elements with an absolute difference equal to k.
Notice that the empty set is a k-Free subset.
Return the number of k-Free subsets of nums.
A subset of an array is a selection of elements (possibly none) of the array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,7,9], k = 3
›
Output:
6
💡 Note:
K-free subsets are: {}, {4}, {7}, {9}, {4,9}, {7,9}. Cannot include {4,7} or {4,7,9} because |4-7|=3=k.
Example 2 — No Conflicts
$
Input:
nums = [2,5,8], k = 4
›
Output:
8
💡 Note:
No two elements differ by 4, so all 2³=8 subsets are k-free: {}, {2}, {5}, {8}, {2,5}, {2,8}, {5,8}, {2,5,8}.
Example 3 — Multiple Conflicts
$
Input:
nums = [1,4,7,10], k = 3
›
Output:
8
💡 Note:
Conflicts: 1-4=3, 4-7=3, 7-10=3. Elements form a chain where adjacent elements can't coexist.
Constraints
- 1 ≤ nums.length ≤ 20
- 1 ≤ nums[i] ≤ 1000
- 0 ≤ k ≤ 1000
- nums contains distinct elements
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[4,7,9] and k=3
2
Find Conflicts
Identify pairs with absolute difference equal to k
3
Count Valid
Count subsets avoiding conflicting pairs
Key Takeaway
🎯 Key Insight: Group elements by remainder mod k to isolate conflicts, then apply DP within each group
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code