The Number of Beautiful Subsets - Problem

You are given an array nums of positive integers and a positive integer k.

A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.

Return the number of non-empty beautiful subsets of the array nums.

A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,6], k = 2
Output: 4
💡 Note: Beautiful subsets are [2], [4], [6], [2,6]. Note that [2,4] and [4,6] are not beautiful since |2-4|=2=k and |4-6|=2=k
Example 2 — Small Array
$ Input: nums = [1], k = 1
Output: 1
💡 Note: Only one subset [1] which is beautiful since it has only one element
Example 3 — No Valid Pairs
$ Input: nums = [4,2,5,9,10,3], k = 1
Output: 23
💡 Note: Many subsets are valid. Elements that differ by 1 cannot be together: (2,3), (4,5), (9,10)

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ nums[i], k ≤ 1000

Visualization

Tap to expand
The Number of Beautiful Subsetsnums = [2,4,6], k = 2246Beautiful Subsets (no pairs with |a-b| = 2):[2][4][6][2,6]Invalid: [2,4] since |2-4|=2=k, [4,6] since |4-6|=2=k, [2,4,6] contains invalid pairsAnswer: 4 beautiful subsets
Understanding the Visualization
1
Input
Array nums=[2,4,6] and k=2 (forbidden difference)
2
Process
Generate all subsets and filter out those with |a-b|=k
3
Output
Count of beautiful subsets: 4
Key Takeaway
🎯 Key Insight: Use backtracking with early pruning to avoid exploring subsets that contain conflicting pairs
Asked in
Amazon 15 Google 10
18.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen