Leetcode #2638: Count the Number of K-Free Subsets
In this guide, we solve Leetcode #2638 Count the Number of K-Free Subsets in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Math, Dynamic Programming, Combinatorics, Sorting
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: nums = [5,4,6], k = 1
Output: 5
Explanation: There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}.
Python Solution
class Solution:
def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int:
nums.sort()
g = defaultdict(list)
for x in nums:
g[x % k].append(x)
ans = 1
for arr in g.values():
m = len(arr)
f = [0] * (m + 1)
f[0] = 1
f[1] = 2
for i in range(2, m + 1):
if arr[i - 1] - arr[i - 2] == k:
f[i] = f[i - 1] + f[i - 2]
else:
f[i] = f[i - 1] * 2
ans *= f[m]
return ans
Complexity
The time complexity is and the space complexity is , where is the length of the array . The space complexity is , where is the length of the array .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.