Similar Problems

Similar Problems not available

The Number Of Beautiful Subsets - Leetcode Solution

Companies:

LeetCode:  The Number Of Beautiful Subsets Leetcode Solution

Difficulty: Medium

Topics: backtracking sorting array dynamic-programming  

The Number of Beautiful Subsets problem on LeetCode asks you to find the number of beautiful subsets of a given array. A beautiful subset is defined as a subset where the bitwise AND of all its elements is equal to its maximum element.

To solve this problem, we can use a bitmasking approach. We can iterate through all possible subsets of the given array using a bitmask. For each subset, we can calculate its bitwise AND and compare it with its maximum element. If they are equal, then the subset is beautiful and we can count it.

Here's the detailed solution for the problem:

  1. Initialize a variable 'count' to 0 to keep track of the number of beautiful subsets.

  2. Iterate over all possible bitmasks from 0 to 2^n - 1, where n is the length of the array.

  3. For each bitmask, iterate over the array and check if the corresponding element is set in the bitmask. If it is set, add it to a new array 'subset'.

  4. Calculate the bitwise AND of all the elements in the 'subset' array. Also, find the maximum element in the 'subset'.

  5. If the bitwise AND is equal to the maximum element, then increment the 'count' variable.

  6. Return the 'count' variable.

Here's the Python code for the solution:

def countBeautifulSubsets(nums: List[int]) -> int: n = len(nums) count = 0

for mask in range(1 << n):
    subset = []
    for i in range(n):
        if mask & (1 << i):
            subset.append(nums[i])
    if subset:
        bitwiseAnd = subset[0]
        maxElement = subset[0]
        for i in range(1, len(subset)):
            bitwiseAnd &= subset[i]
            maxElement = max(maxElement, subset[i])
        if bitwiseAnd == maxElement:
            count += 1

return count

The time complexity of this solution is O(3^n), where n is the length of the array. However, since the maximum value of n is 20, this solution should work efficiently for small inputs.

The Number Of Beautiful Subsets Solution Code

1