Problem Description
Given an array of positive integers, find the size of the largest combination (i.e. subsequence) from the array such that the bitwise AND of all the numbers in that combination is greater than zero.
Key Insights
- The bitwise AND of a set of numbers is greater than zero if and only if there exists at least one bit position that is set (i.e. 1) in every number of the combination.
- Instead of checking every combination, realize that if you select numbers sharing a common bit, then their bitwise AND will have that bit set and be greater than zero.
- Count how many numbers in the array have each particular bit set. The answer is the maximum count among all bit positions.
- The maximum candidate value is up to 10^7, so only a limited number of bits (about 25-32) need to be considered.
Space and Time Complexity
Time Complexity: O(n * B) where n is the number of elements and B is the number of bits we check (B is constant ~ 32). Space Complexity: O(1), as we only use a fixed-size counter for bits.
Solution
To solve this problem, we use the following algorithm:
- Initialize an array (or dictionary) to count occurrences for each bit position.
- Loop through each number in the candidates array.
- For each number, for every bit position (from 0 to 31), check if that bit is set. If yes, increment the count for that bit.
- The largest combination that can produce a bitwise AND greater than zero is the maximum count found among all bit positions. This is because each such count represents the number of candidates that share that specific bit.
- Return the maximum count.
Key data structure: a fixed size array (or simple integer counts for each bit) to tally counts, ensuring the solution is efficient.