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 Subsets INPUT Array nums: 2 idx 0 4 idx 1 6 idx 2 k = 2 Beautiful subset rule: No two elements with |a - b| = k Conflicting pairs: (2,4): |2-4|=2 (4,6): |4-6|=2 (2,6): |2-6|=4 OK ALGORITHM STEPS 1 Group by remainder nums[i] % k groups elements 2 Sort each group Group 0: [2,4,6] 3 DP for each group Skip or take (avoid conflicts) 4 Multiply group counts Subtract 1 (empty set) Subset Enumeration: {2} - beautiful {4} - beautiful {6} - beautiful {2,4} - NOT (diff=2) {4,6} - NOT (diff=2) {2,6} - beautiful FINAL RESULT All 7 non-empty subsets: {2} OK {4} OK {6} OK {2,4} X (k=2) {2,6} OK {4,6} X (k=2) {2,4,6} X Beautiful: 4 | Invalid: 3 Output: 4 4 beautiful subsets found Key Insight: Group elements by (num % k) since conflicts only occur within same remainder group. Use DP similar to House Robber: for each element, either skip it or include it (if no conflict with previous). Time: O(n log n), Space: O(n). Multiply counts across groups, subtract 1 for empty set. TutorialsPoint - The Number of Beautiful Subsets | Optimal Solution (DP with Grouping)
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