Count the Number of K-Free Subsets — LeetCode 2638 Python Solution
MediumLeetCode PremiumArrayMathDynamic ProgrammingCombinatoricsSorting
- Problem
- #2638
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n), where n is the length of the array nums auxiliary |
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
LeetCode 368Largest Divisible SubsetMediumLeetCode 1363Largest Multiple of ThreeHardLeetCode 1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardLeetCode 1478Allocate MailboxesHardLeetCode 1569Number of Ways to Reorder Array to Get Same BSTHardLeetCode 1643Kth Smallest InstructionsHard
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 \times \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.