#2044
Count Number of Maximum Bitwise-OR Subsets
MediumArrayBacktrackingBit ManipulationEnumerationBit ManipulationEnumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating all subsets, we can find the maximum bitwise OR directly by ORing all elements together. Then, we count how many subsets can achieve this maximum OR using the unique elements contributing to it.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the maximum bitwise OR by ORing all elements in the array.
- 2Step 2: Identify which elements contribute to this maximum OR.
- 3Step 3: Count the number of subsets formed by these elements using the formula 2^k - 1, where k is the count of unique elements contributing to the maximum OR.
solution.py13 lines
1# Full working Python code
2def countMaxBitwiseOR(nums):
3 max_or = 0
4 for num in nums:
5 max_or |= num
6 count = 0
7 for num in nums:
8 if (max_or & num) == num:
9 count += 1
10 return (1 << count) - 1
11
12# Example usage
13print(countMaxBitwiseOR([3, 1])) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we traverse the array twice: once to calculate the maximum OR and once to count the contributing elements. The space complexity is O(1) as we only use a few variables.
- 1The maximum bitwise OR can be obtained by ORing all elements together.
- 2Counting subsets can be simplified by focusing on the unique elements that contribute to the maximum OR.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.