The Number of Beautiful Subsets

Medium Topics Company Tags

Count the nonempty subsets of indices of nums for which no two chosen values have absolute difference exactly k. Different choices of indices count separately, even when equal values make the chosen value lists identical. Return the count.

Example 1:

Input: nums = [1,3,5]
k = 2

Output: 4

Explanation: The three single-element subsets are valid. The pair [1,5] is also valid because its difference is 4. Any subset containing [1,3] or [3,5] is invalid, so the answer is 4.

Example 2:

Input: nums = [2,2,4]
k = 2

Output: 4

Explanation: Either occurrence of 2 can be chosen alone, both occurrences can be chosen together, or 4 can be chosen alone. Those are four distinct index subsets. Combining a 2 with 4 is forbidden.

Example 3:

Input: nums = [1,2,3]
k = 5

Output: 7

Explanation: No pair differs by 5. Every nonempty subset is valid, giving 2 cubed minus 1 = 7 subsets.

Constraints:

  • 1 <= nums.length <= 18
  • 1 <= nums[i] <= 1000
  • 1 <= k <= 1000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.