Count the Number of K-Free Subsets — LeetCode 2638 Python Solution

MediumLeetCode PremiumArrayMathDynamic ProgrammingCombinatoricsSorting
Problem
#2638
Pattern
Sorting
Reading time
3 min

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 ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview