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 Subsets INPUT Integer Array nums 3 index 0 1 index 1 Binary Form 3 = 011 1 = 001 All Non-Empty Subsets {3} {1} {3, 1} ALGORITHM STEPS 1 Find Max OR OR all elements: 3|1 = 3 2 Bit Analysis maxOR = 011 (binary) 3 Enumerate Subsets Check each subset's OR 4 Count Matches Count subsets = maxOR OR Calculations {3} --> 3 = 011 OK {1} --> 1 = 001 X {3,1} --> 3|1 = 011 OK maxOR = 3 (011) FINAL RESULT Maximum OR Value maxOR = 3 Subsets with OR = 3 {3} {3,1} 2 subsets achieve maxOR OUTPUT 2 Key Insight: The maximum OR is always achieved by OR-ing all elements together. For bit analysis, we enumerate 2^n - 1 non-empty subsets and count those matching maxOR. Time: O(2^n * n) | Space: O(1) | Using bitmask iteration for subset generation TutorialsPoint - Count Number of Maximum Bitwise-OR Subsets | Optimized with Bit Analysis
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