Count the Number of K-Free Subsets - Problem
Count the Number of K-Free Subsets

You're given an integer array nums containing distinct elements and an integer k. Your task is to count how many subsets are k-free.

A subset is called k-free if it contains no two elements whose absolute difference equals k. In other words, for any two elements a and b in a k-free subset, |a - b| โ‰  k.

Important: The empty set is always considered a k-free subset.

Goal: Return the total number of k-free subsets of the given array.

Example: If nums = [2, 4, 6] and k = 2, then subsets like {2, 6} are k-free (since |2-6| = 4 โ‰  2), but {2, 4} is not k-free (since |2-4| = 2 = k).

Input & Output

example_1.py โ€” Basic case
$ Input: {"nums": [4, 2, 5, 9, 10, 3], "k": 1}
โ€บ Output: 24
๐Ÿ’ก Note: After sorting: [2,3,4,5,9,10]. Chain 1: [2,3,4,5] gives 8 ways (House Robber DP), Chain 2: [9,10] gives 3 ways. Total: 8 ร— 3 = 24.
example_2.py โ€” No conflicts
$ Input: {"nums": [2, 7, 4], "k": 1}
โ€บ Output: 8
๐Ÿ’ก Note: No two elements have difference of 1, so all elements are independent. Each can be included or excluded: 2^3 = 8 subsets total.
example_3.py โ€” Single element
$ Input: {"nums": [1], "k": 1}
โ€บ Output: 2
๐Ÿ’ก Note: Only one element, so we have 2 subsets: {} (empty) and {1}. Both are k-free since there are no pairs to violate the constraint.

Constraints

  • 0 โ‰ค nums.length โ‰ค 20
  • All elements in nums are distinct
  • -106 โ‰ค nums[i] โ‰ค 106
  • 1 โ‰ค k โ‰ค 106

Visualization

Tap to expand
K-Free Subsets: Chain FormationStep 1: Form Chains (k = 1)2345Chain 1: Cannot pick adjacent910Chain 2: Cannot pick adjacentStep 2: House Robber DP on Each ChainChain 1 [2,3,4,5]: dp = [1,2,3,5,8] โ†’ 8 waysChain 2 [9,10]: dp = [1,2,3] โ†’ 3 waysHouse Robber Recurrencedp[i] = dp[i-1] + dp[i-2]dp[i-1]: don't take current elementdp[i-2]: take current element (skip previous)Step 3: Multiply Independent ChainsTotal K-Free Subsets: 8 ร— 3 = 24
Understanding the Visualization
1
Identify Conflict Chains
Elements that differ by k form chains - like people who conflict sitting next to each other
2
Apply House Robber Logic
In each chain, we can't pick adjacent elements - classic House Robber problem
3
Combine Independent Results
Different chains are independent, so multiply their results together
Key Takeaway
๐ŸŽฏ Key Insight: Elements differing by k form chains where we can't pick adjacent elements - this transforms the problem into multiple independent House Robber subproblems!
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
34.2K Views
Medium Frequency
~25 min Avg. Time
1.5K 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