KatInterview

Maximum Group Size with Shared Bit Position

Math & Bit ManipulationAuto-graded · 18 test cases
EasyAuto-gradedMath & Bit Manipulationbit-manipulationgreedycounting

Last updated

Tests ability to use bit manipulation and counting to find the largest group of numbers sharing at least one common bit.

You are given an array of positive integers. Your task is to determine the maximum number of integers you can select such that their bitwise AND result is positive (greater than zero).

A bitwise AND of multiple numbers is positive when at least one bit position contains a 1 in all selected numbers. In other words, the selected numbers must share at least one common bit set to 1 at the same position.

Write a function that returns the size of the largest such selection.

Constraints

  • 1 <= len(nums) <= 100,000
  • 1 <= nums[i] <= 1,000,000,000
  • All integers are positive

Notes

  • You need only return the count, not the actual subset
  • The bitwise AND of a single number is the number itself (always positive for positive integers)
  • Consider all bit positions from 0 to 30 (since values are less than 2^30)

Examples

Example 1

Input: max_and_group_size([1, 2, 3, 4])

Output: 2

Example 2

Input: max_and_group_size([16, 17, 18, 19])

Output: 4

Hints

Hint 1

Think about what it means for a bitwise AND to be positive - which bit positions matter?

Hint 2

For each bit position, count how many numbers have that bit set to 1.

Hint 3

The answer is related to the bit position that appears most frequently across all numbers.