Count Number of Maximum Bitwise-OR Subsets - Problem

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).

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1]
Output: 2
💡 Note: Maximum OR is 3|1 = 3. Subsets [3] and [3,1] both achieve OR = 3, so return 2.
Example 2 — Single Element
$ Input: nums = [2,2,2]
Output: 7
💡 Note: Maximum OR is 2. All non-empty subsets ([2], [2], [2], [2,2], [2,2], [2,2], [2,2,2]) achieve OR = 2.
Example 3 — Different Bits
$ Input: nums = [3,2,1,5]
Output: 6
💡 Note: Maximum OR is 3|2|1|5 = 7. Count all subsets that achieve OR = 7.

Constraints

  • 1 ≤ nums.length ≤ 16
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Count Maximum Bitwise-OR Subsets31Binary: 11Binary: 01Maximum OR = 3 | 1 = 11₂ = 3[3]: OR = 3 ✓[1]: OR = 1 ✗[3,1]: OR = 3 ✓2 subsets achieve maximum OR valueAnswer: 2
Understanding the Visualization
1
Input Array
Given array [3,1] with elements to form subsets
2
Find Max OR
Maximum OR = 3|1 = 3 (all bits from all elements)
3
Count Subsets
Count subsets with OR = 3: [3] and [3,1]
Key Takeaway
🎯 Key Insight: Maximum OR is achieved by ORing all elements, then count subsets with this value
Asked in
Microsoft 15 Google 12
28.4K Views
Medium Frequency
~15 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