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
K-Free Subsets: nums=[4,7,9], k=3479|4-7|=3Conflict: Elements 4 and 7 cannot both be in same subsetValid: {}Valid: {4}Valid: {7}Valid: {9}Valid: {4,9}Invalid: {4,7}Valid: {7,9}Result: 6 k-free subsets
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
Asked in
Google 35 Amazon 28 Microsoft 22
23.5K Views
Medium Frequency
~25 min Avg. Time
845 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