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
Count the Number of K-Free Subsets INPUT nums array: 4 7 9 Index: 0 1 2 k = 3 Conflicts (diff = k): 4 7 |7-4| = 3 = k nums = [4, 7, 9] k = 3 ALGORITHM STEPS 1 Group by remainder nums[i] % k groups 4%3=1, 7%3=1 9%3=0 2 Sort each group Group1: [4,7], Group2: [9] 3 DP on each group Count valid subsets Group [4,7]: skip or take dp[4]=2, dp[7]=2 (conflict!) Subsets: {}, {4}, {7} = 3 Group [9]: {}, {9} = 2 4 Multiply results 3 x 2 = 6 total subsets FINAL RESULT All K-Free Subsets: { } {4} {7} {9} {4, 9} {7, 9} Invalid (excluded): {4, 7} |7-4|=3 Output: 6 OK - 6 valid subsets found Key Insight: Elements with same remainder (num % k) can conflict. Group elements by remainder, then use DP within each sorted group: if consecutive elements differ by k, can't both be in subset. Multiply counts across independent groups. Time: O(n log n), Space: O(n). TutorialsPoint - Count the Number of K-Free Subsets | Optimal Solution
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