Bird
Raised Fist0
Interview Prepsubsets-combinationsmediumAmazonGoogle

Count Number of Max Bitwise-OR Subsets

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

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
</>
IDE
def countMaxOrSubsets(nums: list[int]) -> int:public int countMaxOrSubsets(int[] nums)int countMaxOrSubsets(vector<int>& nums)function countMaxOrSubsets(nums)
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
t1_01basic
Input{"nums":[3,1]}
Expected2

The maximum bitwise OR is 3. The subsets with OR=3 are [3] and [3,1].

t1_02basic
Input{"nums":[1,2,4]}
Expected1

Maximum OR is 7 (1|2|4). Only the full subset [1,2,4] achieves OR=7.

t2_01edge
Input{"nums":[]}
Expected0

Empty input means no non-empty subsets exist, so count is 0.

t2_02edge
Input{"nums":[7]}
Expected1

Single element array has only one non-empty subset: itself, so count is 1.

t2_03edge
Input{"nums":[0,0,0]}
Expected7

All elements zero; max OR is 0. All non-empty subsets have OR=0. Number of non-empty subsets is 2^3 - 1 = 7.

t3_01corner
Input{"nums":[1,2,4,8]}
Expected1

Distinct powers of two; max OR is 15 (1|2|4|8). Only full subset achieves max OR.

t3_02corner
Input{"nums":[5,1,5]}
Expected5

Max OR is 5. Subsets with OR=5 are [5], [5], [5,1], [5,5], [5,1,5].

t3_03corner
Input{"nums":[1,2,3]}
Expected3

Max OR is 3. Subsets with OR=3 are [3], [1,2], [1,2,3].

t4_01performance
Input{"nums":[65535,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2]}
⏱ Performance - must finish in 2000ms

n=16, maximum input size. Algorithm must run in O(n*2^n) time within 2 seconds.

Practice

(1/5)
1. Consider the following Python code implementing the optimal backtracking solution for Combination Sum II. What is the final returned list when calling combinationSum2([1,2,2], 4)?
easy
A. [[1,2,2]]
B. [[1,2],[2]]
C. [[1,2],[2,2]]
D. [[1,2],[2,2],[1,2,2]]

Solution

  1. Step 1: Sort candidates and start backtracking

    Sorted candidates: [1,2,2]. Start from index 0 with target=4.
  2. Step 2: Explore combinations skipping duplicates at same level

    Try 1 -> target=3, then try 2 at next index -> target=1, next 2 is duplicate at same level skipped. No further candidates fit. Backtrack and try 2 at index 1 -> target=2, next 2 at index 2 -> target=0, add [2,2]. Both [1,2,2] and [2,2] are valid unique combinations.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Both [1,2,2] and [2,2] sum to 4 without reuse and duplicates skipped [OK]
Hint: Duplicate skipping prevents repeated combinations [OK]
Common Mistakes:
  • Including partial sums like [2]
  • Allowing reuse of elements
  • Not skipping duplicates at same recursion level
2. The following code attempts to solve Combination Sum (Reuse Allowed). Identify the line containing the subtle bug that causes incorrect results or inefficiency:
def combinationSum(candidates, target):
    candidates.sort()
    result = []
    def backtrack(index, path, target):
        if target == 0:
            result.append(path[:])
            return
        if index == len(candidates) or target < 0:
            return
        max_use = target // candidates[index]
        for count in range(max_use + 1):
            path += [candidates[index]] * count
            backtrack(index + 1, path, target - candidates[index] * count)
            # Missing path restoration here
    backtrack(0, [], target)
    return result
medium
A. Line with 'path += [candidates[index]] * count' because path is modified without backtracking (pop).
B. Line with 'candidates.sort()' because sorting is unnecessary.
C. Line with 'if target == 0:' because it should check for target <= 0.
D. Line with 'max_use = target // candidates[index]' because integer division may cause errors.

Solution

  1. Step 1: Analyze path modification in loop

    Path is extended by count copies of candidates[index] but never restored after recursive call, causing path to grow incorrectly across iterations.
  2. Step 2: Identify missing backtracking step

    Proper backtracking requires removing added elements after recursion to restore path state for next iteration.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Modifying path without restoration leads to incorrect combinations [OK]
Hint: Always restore path after recursion in backtracking [OK]
Common Mistakes:
  • Forgetting to pop elements after recursion
  • Assuming path copy avoids mutation issues
3. What is the time complexity of the iterative lexicographic combinations generation algorithm for generating all combinations of size k from n elements?
medium
A. O(n^k) because each element can be chosen or not
B. O(k * (n choose k)) since each combination of size k is generated once and updated in O(k)
C. O(\u03C3(n choose k) * k) where \u03C3 is the number of combinations generated
D. O(n * k) because the outer loop runs n times and inner loop k times

Solution

  1. Step 1: Identify number of combinations

    There are exactly (n choose k) combinations to generate.
  2. Step 2: Analyze per-combination cost

    Each combination is generated and updated in O(k) time due to copying and resetting elements.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Time is proportional to number of combinations times combination size [OK]
Hint: Time depends on number of combinations times k [OK]
Common Mistakes:
  • Confusing with exponential O(n^k) or linear O(n*k) complexities
4. The following code attempts to generate all unique subsets from an array with duplicates. Which line contains a subtle bug that causes incorrect or duplicate subsets?
medium
A. Line 9: if i > 0 and nums[i] == nums[i - 1]: s = 0
B. Line 13: res.append(res[j] + [nums[i]])
C. Line 11: start = len(res)
D. Line 6: nums.sort()

Solution

  1. Step 1: Understand the role of variable s

    Variable s determines the start index for adding new subsets. For duplicates, s should be set to the previous start to avoid duplicates.
  2. Step 2: Identify the bug in line 9

    Setting s = 0 for duplicates causes subsets to be appended from the beginning, generating duplicate subsets. The correct logic is to set s = start (previous length) to skip duplicates only at the same recursion level.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Incorrect s causes duplicate subsets [OK]
Hint: Duplicate skipping must use previous start index [OK]
Common Mistakes:
  • Setting s=0 always for duplicates
  • Not sorting input before processing
  • Appending without proper start index
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

  1. Step 1: Understand reuse requirement

    Allowing unlimited reuse means after including an element, we can include it again without advancing index.
  2. Step 2: Modify recursion accordingly

    Recurse twice: include current element and recurse with same index, or exclude and recurse with next index.
  3. 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.
  4. Final Answer:

    Option A -> Option A
  5. 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