Count the Number of K-Free Subsets Problem
Description
LeetCode Problem 2638.
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.
Example 1:
Input: nums = [5,4,6], k = 1
Output: 5
Explanation: There are 5 valid subsets: {}, {5}, {4}, {6} and {4, 6}.
Example 2:
Input: nums = [2,3,5,8], k = 5
Output: 12
Explanation: There are 12 valid subsets: {}, {2}, {3}, {5}, {8}, {2, 3}, {2, 3, 5}, {2, 5}, {2, 5, 8}, {2, 8}, {3, 5} and {5, 8}.
Example 3:
Input: nums = [10,5,9,11], k = 20
Output: 16
Explanation: All subsets are valid. Since the total count of subsets is 2^4= 16, so the answer is 16.
Constraints:
1 <= nums.length <= 501 <= nums[i] <= 10001 <= k <= 1000
Solution
Approach: Group by Remainder + DP
Two numbers can only differ by exactly k if they have the same remainder modulo k. So split the numbers into groups by x % k; the groups do not interact, and the answer is the product of the number of valid subsets of each group.
Within a group, sort the values. Only neighbours in this order can differ by k. Let f[i] be the number of valid subsets of the first i values of the group, with f[0] = 1 and f[1] = 2. For i >= 2:
- If
arr[i - 1] - arr[i - 2] == k, the two cannot both be chosen: skipping the last givesf[i - 1]subsets and taking it forces skipping the previous one, givingf[i - 2]. Sof[i] = f[i - 1] + f[i - 2]. - Otherwise the last value is free to take or skip, so
f[i] = 2 * f[i - 1].
Multiply f[m] over all groups. This counts the empty subset too, as the problem requires.
Complexity: O(n log n) time for the sort and O(n) space, where n is the length of nums.
from collections import defaultdict
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