Largest Combination With Bitwise AND Greater Than Zero - Problem

You're given an array of positive integers called candidates. Your task is to find the largest possible combination (subset) of these numbers such that their bitwise AND is greater than zero.

The bitwise AND of an array is calculated by performing the AND operation on all integers in the array:

  • For [1, 5, 3]: 1 & 5 & 3 = 1 (result > 0 ✓)
  • For [7]: the bitwise AND is simply 7 (result > 0 ✓)
  • For [2, 4]: 2 & 4 = 0 (result = 0 ✗)

Goal: Return the size of the largest combination where the bitwise AND result is greater than 0.

Key Insight: For a bitwise AND to be greater than 0, at least one bit position must be 1 in all numbers of the combination!

Input & Output

example_1.py — Basic case
$ Input: [16, 17, 71, 62, 12, 24, 14]
Output: 4
💡 Note: The largest combination is [16, 17, 62, 24] with bitwise AND = 16 > 0. All four numbers share bit position 4.
example_2.py — Simple case
$ Input: [8, 8]
Output: 2
💡 Note: Both numbers are identical, so their AND = 8 > 0. We can take both numbers.
example_3.py — Single element
$ Input: [1]
Output: 1
💡 Note: With only one element, the largest (and only) combination has size 1.

Visualization

Tap to expand
🎯 Team Formation StrategyPerson16Skills: 4Person17Skills: 0,4Person71Skills: 0,1,2,6Person62Skills: 1,2,3,4,5Skill AnalysisSkill 0: 2 people (17, 71)Skill 1: 2 people (71, 62)Skill 2: 2 people (71, 62)Skill 3: 1 person (62)Skill 4: 3 people (16, 17, 62) ← LARGEST TEAM!Maximum Team Size: 3
Understanding the Visualization
1
Identify Skills
Each bit position represents a different skill
2
Count Per Skill
Count how many people have each skill
3
Find Best Team
The skill with the most people gives us the largest team
Key Takeaway
🎯 Key Insight: Instead of trying all team combinations, just find the most popular skill!

Time & Space Complexity

Time Complexity
⏱️
O(n × log(max_val))

We check each number against each bit position. With max value 10^7, we need ~24 bit checks per number

n
2n
Linearithmic
Space Complexity
O(1)

Only using a constant-size array for bit counts (max 32 elements)

n
2n
Linear Space

Constraints

  • 1 ≤ candidates.length ≤ 105
  • 1 ≤ candidates[i] ≤ 107
  • All candidates are positive integers
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
24.5K Views
Medium Frequency
~15 min Avg. Time
892 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