#2597

The Number of Beautiful Subsets

Medium
ArrayHash TableMathDynamic ProgrammingBacktrackingSortingCombinatoricsHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a backtracking approach with a frequency array to track the counts of elements, allowing us to efficiently skip adding elements that would violate the beautiful condition. This reduces unnecessary checks and speeds up the process.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the input array nums.
  2. 2Step 2: Create a frequency array to count occurrences of each number.
  3. 3Step 3: Use backtracking to explore subsets, adding elements only if they do not create a conflict with the existing subset.
solution.py24 lines
1# Full working Python code
2from collections import defaultdict
3
4def beautiful_subsets(nums, k):
5    nums.sort()
6    count = 0
7    freq = defaultdict(int)
8    def backtrack(index):
9        nonlocal count
10        if index == len(nums):
11            return
12        # Option to not include nums[index]
13        backtrack(index + 1)
14        # Option to include nums[index]
15        if freq[nums[index] - k] == 0:
16            freq[nums[index]] += 1
17            count += 1  # Count this subset
18            backtrack(index + 1)
19            freq[nums[index]] -= 1
20    backtrack(0)
21    return count
22
23# Example usage
24print(beautiful_subsets([2, 4, 6], 2))  # Output: 4

Complexity note: This complexity arises because we efficiently track the frequency of elements, allowing us to skip checks for subsets that would violate the beautiful condition, thus reducing the overall time taken.

  • 1Sorting helps in managing the conditions for beautiful subsets.
  • 2Using a frequency array allows for quick checks on whether to include an element.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.