Taro Logo

Count Number of Maximum Bitwise-OR Subsets

Medium
Asked by:
Google
Amazon
Citadel
Microsoft
239 views
Topics:
Bit ManipulationDynamic ProgrammingRecursion

Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.

An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.

The bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).

Example 1:

Input: nums = [3,1]
Output: 2
Explanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]

Example 2:

Input: nums = [2,2,2]
Output: 7
Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.

Example 3:

Input: nums = [3,2,1,5]
Output: 6
Explanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]

Constraints:

  • 1 <= nums.length <= 16
  • 1 <= nums[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the size of the array `nums` and the range of values inside it?
  2. Can the array contain negative integers, or are all numbers guaranteed to be non-negative?
  3. Since the problem mentions subsets, are subsets with the same elements derived from different indices considered distinct subsets?
  4. Is the input array guaranteed to be non-empty, and what should be returned if an empty array is somehow passed?
  5. Does the order of elements in the subset matter when calculating the bitwise-OR value?

Brute Force Solution

Approach

To find how many groups of items can be formed to reach the highest possible combined value, we can simply test every single possible group combination that can be made from the given collection. By looking at every possible grouping, we can calculate each group's combined value, find the overall maximum value, and count how many groups achieved that maximum.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the entire collection of items provided to you.
  2. Imagine creating a list of every possible combination of items you could ever pick, ranging from picking just a single item to picking all of them together.
  3. For every single combination you just listed, apply the combining rule to figure out the final combined value of that specific group.
  4. Keep a record of all these calculated combined values alongside their respective groups.
  5. Scan through all the calculated values to find the absolute highest one that was achieved by any group.
  6. Go back through your records and count how many different groups managed to reach that exact highest value.
  7. Deliver that final count as your answer.

Code Implementation

class Solution:
    def countMaxOrSubsets(self, nums: list[int]) -> int:
        from itertools import combinations
        
        all_subsets = []
        
        for subset_size in range(1, len(nums) + 1):
            for current_combination in combinations(nums, subset_size):
                all_subsets.append(current_combination)
        
        calculated_values = []
        
        for subset_group in all_subsets:
            current_bitwise_or = 0
            for number in subset_group:
                current_bitwise_or |= number
            calculated_values.append(current_bitwise_or)
        
        # We need to find the absolute highest bitwise-OR value across all generated subsets
        maximum_bitwise_or = max(calculated_values)
        
        maximum_count = 0
        
        for group_value in calculated_values:
            if group_value == maximum_bitwise_or:
                maximum_count += 1
        
        return maximum_count

Big(O) Analysis

Time Complexity
O(2ⁿ) – The strategy involves generating and checking every possible subset of the input array, where each of the n elements can either be included or excluded. Because there are 2ⁿ total unique combinations of subsets, the algorithm must evaluate the bitwise-OR value for all 2ⁿ groups. As the input size n increases, the number of combinations grows exponentially. This leads to approximately 2ⁿ subset evaluations, which simplifies to the final time complexity of O(2ⁿ).
Space Complexity
O(n) – The space complexity is driven by the recursion stack used to explore every possible subset combination from the input collection of size N. As the algorithm traverses all possible groupings, the maximum depth of the recursive calls reaches N, requiring auxiliary memory proportional to the input size. Additionally, a few primitive variables are maintained to track the current bitwise-OR value and the maximum count, but their memory usage remains constant. Therefore, the total extra memory scales directly with the maximum depth of the recursion tree, leading to a linear space complexity.

Optimal Solution

Approach

To find the subsets that achieve the highest possible bitwise-OR value, we first need to figure out what that maximum possible value is by combining every single number together. Then, we systematically explore the different combinations of numbers to see how many of them reach that exact maximum target.

Here's how the algorithm would work step-by-step:

  1. Combine all available numbers together using the bitwise-OR operation to discover the ultimate maximum target value you are trying to reach.
  2. Imagine holding a collection of items where you make a simple yes-or-no decision for every single item about whether to include it in your current group.
  3. Start with an empty group and gradually consider every item one by one, branching out to test both possibilities: including the current item or leaving it out.
  4. As you build each combination, keep track of its combined value using the bitwise-OR operation.
  5. Whenever a combination is fully formed, check if its combined value matches the ultimate maximum target you calculated at the very beginning.
  6. Every time you find a combination that hits the target value, keep a tally of it as a successful match.
  7. Explore every single path of choices until all possible combinations have been tested, and report your final winning tally.

Code Implementation

class Solution:
    def count_max_or_subsets(self, numbers_list: list[int]) -> int:
        maximum_target_value = 0
        for number in numbers_list:
            maximum_target_value |= number

        successful_matches_tally = 0

        def explore_combinations(current_index: int, current_bitwise_or: int):
            nonlocal successful_matches_tally
            
            # We stop exploring further when all numbers have been considered.
            if current_index == len(numbers_list):
                if current_bitwise_or == maximum_target_value:
                    successful_matches_tally += 1
                return

            # Branch out by including the current number in our combination group.
            explore_combinations(current_index + 1, current_bitwise_or | numbers_list[current_index])

            # Branch out again by leaving the current number out of our group.
            explore_combinations(current_index + 1, current_bitwise_or)

        explore_combinations(0, 0)
        return successful_matches_tally

Big(O) Analysis

Time Complexity
O(2ⁿ) – To find the maximum bitwise-OR value, we first iterate through all n elements of the array in linear time. Next, we systematically explore every possible subset by making a binary decision of whether to include or exclude each of the n elements. This recursive exploration branches into two choices at each of the n steps, resulting in 2ⁿ total combinations that must be evaluated. Summing the work for the initial pass and the exponential subset generation yields approximately n plus 2ⁿ operations, which simplifies to O(2ⁿ).
Space Complexity
O(N) – The space complexity is driven entirely by the recursion stack used to systematically explore the subsets, where N represents the number of elements in the input array. As the algorithm branches to include or exclude each element one by one, the recursive calls reach a maximum depth of N. Aside from a few constant extra variables to track the current bitwise-OR value and the match tally, no additional data structures are created. Therefore, the total extra memory required is proportional to the maximum depth of the recursion stack, resulting in O(N) auxiliary space.

Edge Cases

Array of minimum size with exactly one element
How to Handle:
The algorithm correctly identifies this single element as both the maximum OR value and the sole subset achieving it, returning a count of one.
Inputs containing zeros
How to Handle:
Since bitwise OR with zero does not change the value, including zeros will duplicate the maximum OR count and must be properly factored into the subset combinations.
Maximum-sized inputs leading to exponential subset growth
How to Handle:
Because the maximum length of nums typically reaches up to sixteen in this problem, a recursive backtracking approach scales efficiently with two to the power of N complexity.
Inputs with all identical values
How to Handle:
The bitwise OR will simply equal that single value, and the subset count will equal two to the power of N minus one since every non-empty combination yields the same OR.
Subsets producing duplicate index combinations but identical values
How to Handle:
The backtracking algorithm naturally evaluates unique index combinations rather than unique values, ensuring every distinct subset is counted independently.
Large integer values within standard bitwise limits
How to Handle:
Standard thirty-two bit integer types natively support the bitwise OR operations without overflow risks since values fit well within standard integer primitives.