Magicsheet logo

Largest Combination With Bitwise AND Greater Than Zero

Medium
82.8%
Updated 6/1/2025

Largest Combination With Bitwise AND Greater Than Zero

1. What is this problem about?

The Largest Combination With Bitwise AND Greater Than Zero interview question asks you to find the maximum number of elements you can pick from an array such that their bitwise AND result is strictly greater than zero. For a bitwise AND of several numbers to be greater than zero, there must be at least one bit position where all chosen numbers have a '1'. If no such bit exists, the result will be 0. The goal is to find the largest subset (combination) that satisfies this condition.

2. Why is this asked in interviews?

This Array, Bit Manipulation interview pattern is popular at companies like Amazon and Microsoft. It tests a candidate's ability to look past the "combination" aspect of the problem—which usually implies exponential complexity—and recognize the underlying bitwise property. It's a test of observation: instead of trying all combinations, can you see that the problem is really about finding which bit position is shared by the most numbers?

3. Algorithmic pattern used

The optimal strategy is to use Counting and Bit Manipulation. Since the numbers are typically within a 32-bit range (often up to 10710^7, fitting in 24 bits), we can iterate through each bit position from 0 to 31. For each bit position ii, we count how many numbers in the input array have their ii-th bit set to 1. The maximum count across all 32 positions will be our answer. This is because any group of numbers that all have the ii-th bit set will have a bitwise AND result of at least 2i2^i, which is greater than zero.

4. Example explanation

Consider the array [16, 17, 71, 62, 12, 24, 14].

  • Let's check the 4th bit (value 16): 16, 17, 24 have this bit set. Count = 3.
  • Let's check the 3rd bit (value 8): 12, 14, 24 have this bit set. Count = 3.
  • Let's check the 1st bit (value 2): 71, 62, 14 have this bit set. Count = 3. Wait, let's look at the bit representations:
  • 16: 10000
  • 17: 10001
  • 71: 1000111
  • 62: 0111110
  • 12: 0001100
  • 24: 0011000
  • 14: 0001110 Checking bit by bit, the bit with the most '1's wins. If bit 4 is set in 4 numbers, the answer is 4.

5. Common mistakes candidates make

  • Trying subsets: Attempting to use backtracking or recursion to find all combinations. With NN up to 10510^5, 2N2^N is impossible.
  • Incorrect bit limit: Only checking up to bit 7 or 15 when the numbers can be much larger.
  • Misunderstanding AND: Thinking that a combination like [1, 2, 4] could work. 1 & 2 & 4 = 0, even though each number is non-zero. They must share a common bit.

6. Interview preparation tip

When dealing with bitwise operators (AND, OR, XOR), always try thinking "bit by bit." Many problems that seem to involve combinations or subsets can be solved by analyzing the behavior of each of the 32 bits independently.

Similar Questions