MediumNo. 2638LeetCode Premium
Count the Number of K-Free Subsets — LeetCode 2638 Python Solution
- Pattern
- Sorting
- Topics
- Array, Math, Dynamic Programming, Combinatorics, Sorting
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
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 ansComplexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)where n is the length of the array nums
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2638. Count the Number of K-Free Subsets is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0368 | Largest Divisible Subset | Medium |
| 1363 | Largest Multiple of Three | Hard |
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard |
| 1478 | Allocate Mailboxes | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 1643 | Kth Smallest Instructions | Hard |
Frequently asked questions
- How hard is LeetCode 2638. Count the Number of K-Free Subsets?
LeetCode 2638. Count the Number of K-Free Subsets is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2638. Count the Number of K-Free Subsets?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2638. Count the Number of K-Free Subsets?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
- What topics does LeetCode 2638. Count the Number of K-Free Subsets cover?
LeetCode 2638. Count the Number of K-Free Subsets is tagged Array, Math, Dynamic Programming, Combinatorics and Sorting on LeetCode.
- Is LeetCode 2638. Count the Number of K-Free Subsets a premium problem?
Yes. LeetCode 2638. Count the Number of K-Free Subsets is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.