Largest Combination With Bitwise AND Greater Than Zero - Problem

The bitwise AND of an array nums is the bitwise AND of all integers in nums.

For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
Also, for nums = [7], the bitwise AND is 7.

You are given an array of positive integers candidates. Compute the bitwise AND for all possible combinations of elements in the candidates array.

Return the size of the largest combination of candidates with a bitwise AND greater than 0.

Input & Output

Example 1 — Basic Case
$ Input: candidates = [16,17,71,62,12,24,14]
Output: 4
💡 Note: The combination [16,17,62,24] has a bitwise AND where bit 4 is set in all numbers, giving AND = 16 > 0. Bit position 4 appears in exactly 4 numbers, which is the maximum across all bit positions.
Example 2 — Small Array
$ Input: candidates = [8,8]
Output: 2
💡 Note: Both numbers are identical, so we can pick both and their AND = 8 > 0.
Example 3 — No Common Bits
$ Input: candidates = [1,2,4,8]
Output: 1
💡 Note: Each number has a unique bit set, so maximum combination size with AND > 0 is 1.

Constraints

  • 1 ≤ candidates.length ≤ 105
  • 1 ≤ candidates[i] ≤ 107

Visualization

Tap to expand
Largest Combination With Bitwise AND > 0 INPUT candidates array: 16 17 71 62 12 24 14 Binary Form (7 bits): 16: 0010000 17: 0010001 71: 1000111 62: 0111110 12: 0001100 24: 0011000 14: 0001110 Bit positions: 6 5 4 3 2 1 0 Goal: Find largest group sharing a common bit ALGORITHM STEPS 1 Count Bits For each bit position (0-23), count how many nums have it set 2 Bit Counting Table Track count per bit position Bit 0: 3 nums (17,71,17) Bit 1: 4 nums (71,62,12,14) Bit 2: 4 nums (71,62,12,14) Bit 3: 4 nums (62,12,24,14) Bit 4: 4 nums (16,17,62,24) Bit 5: 2 nums (62,24) 3 Find Maximum Max count = largest combination 4 Return Result Multiple bits have count = 4 Time: O(n * 24) = O(n) Space: O(24) = O(1) FINAL RESULT Largest combination found: Bit 1 or 2 or 3 or 4 Each has 4 numbers Example (Bit 3): [62, 12, 24, 14] 62 & 12 & 24 & 14 = 8 OUTPUT 4 OK - Maximum size of combination with AND > 0 is 4 Verified: 8 > 0 Key Insight: For bitwise AND to be > 0, at least one bit must be 1 in ALL numbers of the combination. Instead of checking all 2^n combinations, count numbers having each bit set (0-23). The maximum count across all bit positions = largest valid combination size. O(24n) = O(n) solution! TutorialsPoint - Largest Combination With Bitwise AND Greater Than Zero | Optimal Solution (Bit Counting)
Asked in
Meta 25 Google 15
28.5K Views
Medium Frequency
~15 min Avg. Time
890 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