Imagine you have a collection of gadgets, each with a unique set of features represented as bits. You want to find out how many combinations of these gadgets together unlock the maximum possible feature set.
Given an integer array nums, return the number of non-empty subsets of nums such that the bitwise OR of all elements in the subset is equal to the maximum possible bitwise OR of any subset of nums.
Input: An integer array nums.
Output: An integer representing the count of subsets with the maximum bitwise OR.
1 ≤ nums.length ≤ 161 ≤ nums[i] ≤ 10^5
Edge cases: Single element array → output is 1All elements are zero → output is 2^n - 1 (all subsets except empty)All elements are the same non-zero number → output is 2^n - 1
def countMaxOrSubsets(nums):
# Write your solution here
pass
class Solution {
public int countMaxOrSubsets(int[] nums) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int countMaxOrSubsets(vector<int>& nums) {
// Write your solution here
return 0;
}
function countMaxOrSubsets(nums) {
// Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for non-empty input due to missing counting of subsets.✅ Ensure to count subsets when current OR equals max OR, not just when greater.
Wrong: 1Counting only one subset (e.g., full set) without checking all subsets.✅ Enumerate all subsets and count all with OR equal to max OR.
Wrong: 7Counting empty subset or miscomputing OR for empty subset.✅ Exclude empty subset from count explicitly.
Wrong: Incorrect count due to ignoring duplicatesNot enumerating all subsets or merging duplicates incorrectly.✅ Enumerate all subsets including duplicates and count those with max OR.
Wrong: TLEUsing naive brute force without pruning or optimization.✅ Use bitmask enumeration or backtracking with pruning to reduce computations.
✓
Test Cases
Try testing your code on empty and single-element inputs to handle base cases.
Consider tricky inputs with duplicates and powers of two to catch subtle bugs.
Prepare for performance by optimizing subset enumeration and pruning.
t1_01basic
Input{"nums":[3,1]}
Expected2
⏱ Performance - must finish in 2000ms
The maximum bitwise OR is 3. The subsets with OR=3 are [3] and [3,1].
💡 Consider all subsets and compute their bitwise OR values.
💡 Use backtracking or bitmask enumeration to generate subsets and track max OR.
💡 Count subsets whose OR equals the maximum found.
Why it failed: Incorrect count means either max OR not tracked correctly or subsets with max OR not counted properly. Fix by updating max OR and count only when current OR equals max OR.
✓ Correctly identifies max OR and counts all subsets achieving it.
t1_02basic
Input{"nums":[1,2,4]}
Expected1
⏱ Performance - must finish in 2000ms
Maximum OR is 7 (1|2|4). Only the full subset [1,2,4] achieves OR=7.
💡 Check OR of all subsets; max OR is OR of all elements combined.
💡 Only subsets including all elements can reach max OR if elements are distinct powers of two.
💡 Count subsets with OR equal to 7; here only one subset qualifies.
Why it failed: Counting subsets without verifying OR equals max OR leads to wrong count. Fix by comparing each subset OR to max OR before counting.
✓ Correctly counts only subsets with OR equal to max OR.
t2_01edge
Input{"nums":[]}
Expected0
⏱ Performance - must finish in 2000ms
Empty input means no non-empty subsets exist, so count is 0.
💡 Consider what subsets exist when input is empty.
💡 No non-empty subsets means count should be zero.
💡 Return 0 immediately if input is empty.
Why it failed: Returning non-zero count for empty input is wrong. Fix by handling empty input case explicitly.
✓ Correctly returns 0 for empty input.
t2_02edge
Input{"nums":[7]}
Expected1
⏱ Performance - must finish in 2000ms
Single element array has only one non-empty subset: itself, so count is 1.
💡 With one element, max OR is the element itself.
💡 Only one subset to consider: the element alone.
💡 Return 1 for single element input.
Why it failed: Counting empty subset or missing single element subset causes wrong count. Fix by excluding empty subset and including single element subset.
✓ Correctly counts single element subset.
t2_03edge
Input{"nums":[0,0,0]}
Expected7
⏱ Performance - must finish in 2000ms
All elements zero; max OR is 0. All non-empty subsets have OR=0. Number of non-empty subsets is 2^3 - 1 = 7.
💡 When all elements are zero, OR of any subset is zero.
💡 Count all non-empty subsets: 2^n - 1.
💡 Return 7 for n=3 zeros.
Why it failed: Failing to exclude empty subset or miscomputing OR leads to wrong count. Fix by excluding empty subset and recognizing all subsets have OR=0.
✓ Correctly counts all non-empty subsets when all elements are zero.
t3_01corner
Input{"nums":[1,2,4,8]}
Expected1
⏱ Performance - must finish in 2000ms
Distinct powers of two; max OR is 15 (1|2|4|8). Only full subset achieves max OR.
💡 Check if max OR equals OR of all elements combined.
💡 Only full subset can achieve max OR if elements are distinct powers of two.
💡 Count subsets with OR equal to max OR; here only one subset.
Why it failed: Counting subsets missing some elements as max OR subsets is wrong. Fix by ensuring subset OR equals max OR exactly.
✓ Correctly identifies only full subset as max OR subset.
t3_02corner
Input{"nums":[5,1,5]}
Expected5
⏱ Performance - must finish in 2000ms
Max OR is 5. Subsets with OR=5 are [5], [5], [5,1], [5,5], [5,1,5].
💡 Handle duplicates carefully when counting subsets.
💡 Count all subsets whose OR equals max OR, including duplicates.
💡 Use backtracking or bitmask enumeration to avoid missing duplicates.
Why it failed: Ignoring duplicates or double counting subsets causes wrong count. Fix by enumerating all subsets and counting those with OR equal to max OR.
✓ Correctly counts all subsets with duplicates considered.
t3_03corner
Input{"nums":[1,2,3]}
Expected3
⏱ Performance - must finish in 2000ms
Max OR is 3. Subsets with OR=3 are [3], [1,2], [1,2,3].
💡 Avoid greedy approach that picks only largest element.
💡 Check all subsets to find all achieving max OR.
💡 Count subsets with OR equal to max OR, not just those containing max element.
Why it failed: Greedy approach counting only subsets containing max element misses others. Fix by enumerating all subsets and comparing OR to max OR.
✓ Correctly counts all subsets with max OR including those without max element.
n=16, maximum input size. Algorithm must run in O(n*2^n) time within 2 seconds.
💡 Use bitmask enumeration or backtracking with pruning.
💡 Avoid recomputing OR for subsets repeatedly.
💡 Memoize or use iterative subset generation for efficiency.
Why it failed: Brute force exponential without pruning causes TLE. Fix by using DP or pruning to reduce redundant computations.
✓ Algorithm runs within time limit using efficient subset enumeration.
Practice
(1/5)
1. You need to generate all unique groups of size k from numbers 1 to n without repetition, where order within each group does not matter. Which algorithmic approach guarantees generating all such groups efficiently without duplicates?
easy
A. Backtracking that explores all number choices with pruning to avoid duplicates
B. Greedy selection picking the smallest available number until group size is reached
C. Dynamic programming to count subsets but not generate them explicitly
D. Sorting all numbers and then selecting consecutive sequences of length k
Solution
Step 1: Understand the problem requires all unique combinations of size k from n numbers
Greedy or sorting consecutive sequences do not guarantee all unique combinations without duplicates.
Step 2: Backtracking with pruning systematically explores all valid combinations and avoids duplicates by controlling start indices
This approach ensures all unique groups are generated efficiently.
Final Answer:
Option A -> Option A
Quick Check:
Backtracking with pruning is the standard approach for combinations [OK]
Hint: Backtracking with pruning avoids duplicates efficiently [OK]
Common Mistakes:
Thinking greedy or sorting consecutive sequences generate all combinations
2. You need to generate all possible subsets of a given set of distinct integers. Which algorithmic approach guarantees enumerating every subset exactly once, including the empty subset, without missing or duplicating any subset?
easy
A. Greedy algorithm that picks elements based on a heuristic to maximize subset size
B. Dynamic programming approach that builds subsets by summing elements to target values
C. Backtracking with include/exclude decisions at each element to explore all subset combinations
D. Sorting the array and then using two pointers to find pairs that form subsets
Solution
Step 1: Understand problem requirements
The problem requires enumerating all subsets, which means exploring all combinations of including or excluding each element.
Step 2: Identify suitable algorithm
Backtracking with include/exclude decisions systematically explores all subsets without duplication or omission, including the empty subset.
Final Answer:
Option C -> Option C
Quick Check:
Backtracking ensures all subsets are generated [OK]
Hint: Include/exclude backtracking covers all subsets [OK]
Common Mistakes:
Confusing subset generation with greedy or DP sum problems
3. Suppose the problem is modified so that numbers 1 to 9 can be reused any number of times in combinations summing to n with size k. Which change to the backtracking algorithm correctly handles this variant?
hard
A. Add a visited set to prevent reusing numbers and keep backtrack(i + 1, comb, total + i)
B. Keep the recursive call as backtrack(i + 1, comb, total + i) but allow duplicates in the result
C. Change the recursive call to backtrack(i, comb, total + i) to allow reuse of the same number i
D. Use a dynamic programming approach instead of backtracking to handle reuse efficiently
Solution
Step 1: Understand reuse requirement
Allowing reuse means the same number can be chosen multiple times, so next recursion should start at current number i, not i+1.
Step 2: Modify recursive call
Change backtrack(i + 1, ...) to backtrack(i, ...) to allow repeated picks of i.
Step 3: Confirm correctness
This change correctly explores combinations with repeated numbers without duplicates.
Final Answer:
Option C -> Option C
Quick Check:
Recursing with start=i enables reuse of number i [OK]
Hint: Reuse requires recursive calls with start index unchanged [OK]
Common Mistakes:
Not changing start index to allow reuse
Allowing duplicates by mistake
Switching to DP unnecessarily
4. Suppose the problem changes: now candidates can include negative numbers, and you still want all unique combinations summing to the target with reuse allowed. Which modification to the backtracking approach is necessary to handle this variant correctly?
hard
A. Remove pruning on target < 0 and add a visited set to detect cycles to avoid infinite recursion.
B. No change needed; the existing backtracking with pruning on target < 0 still works correctly.
C. Sort candidates in descending order and prune when target is less than the smallest candidate.
D. Use dynamic programming instead of backtracking because negative numbers break recursion.
Solution
Step 1: Understand impact of negative candidates
Negative numbers allow sums to decrease indefinitely, causing infinite recursion if pruning on target < 0 is used or missing.
Step 2: Modify pruning and cycle detection
Pruning on target < 0 is invalid because target can oscillate; must remove it and add a visited set or memoization to detect repeated states and avoid infinite loops.
Final Answer:
Option A -> Option A
Quick Check:
Cycle detection is essential when negative numbers allow infinite recursion [OK]
5. Suppose you want to generate all subsets of nums but now elements can be reused unlimited times in each subset (i.e., multisets). Which modification to the backtracking approach correctly handles this?
hard
A. At each recursion step, recurse twice: once including current element and staying at same index to allow reuse, once excluding and moving to next index
B. At each recursion step, recurse with index + 1 only, excluding current element to avoid duplicates
C. Use bit manipulation as before, but allow bits to be set multiple times to represent reuse
D. Sort the array and use two pointers to generate subsets with repeated elements
Solution
Step 1: Understand reuse requirement
Allowing unlimited reuse means after including an element, we can include it again without advancing index.
Step 2: Modify recursion accordingly
Recurse twice: include current element and recurse with same index, or exclude and recurse with next index.
Step 3: Why other options fail
At each recursion step, recurse with index + 1 only, excluding current element to avoid duplicates excludes reuse by always advancing index; Use bit manipulation as before, but allow bits to be set multiple times to represent reuse is invalid as bitmask can't represent multiple counts; Sort the array and use two pointers to generate subsets with repeated elements is unrelated.
Final Answer:
Option A -> Option A
Quick Check:
Staying at same index after include enables repeated elements [OK]
Hint: Reuse means recurse with same index after include [OK]
Common Mistakes:
Advancing index after include prevents reuse
Trying bitmask for multisets
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.