#2275

Largest Combination With Bitwise AND Greater Than Zero

Medium
ArrayHash TableBit ManipulationCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that for the bitwise AND to be greater than zero, we can focus on each bit position and count how many numbers have that bit set. The maximum count for any bit position gives us the size of the largest combination.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array to count occurrences of each bit position (up to 24 bits).
  2. 2Step 2: For each number in the candidates, update the count for each bit position that is set (1).
  3. 3Step 3: The maximum value in the count array is the size of the largest combination with a bitwise AND greater than 0.
solution.py7 lines
1def largestCombination(candidates):
2    count = [0] * 24
3    for num in candidates:
4        for i in range(24):
5            if num & (1 << i):
6                count[i] += 1
7    return max(count)

Complexity note: The time complexity is O(n) because we iterate through the candidates once and check each of the 24 bits, which is a constant factor.

  • 1The bitwise AND operation requires at least one bit to be 1 in all numbers for the result to be greater than 0.
  • 2Focusing on individual bit positions allows us to efficiently count potential combinations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.