Katkat

Largest Subset With Positive Bitwise AND

Jump TradingSoftware Engineer · Technical Screen

Last updated

This problem tests your understanding of bitwise operations and greedy array partitioning to maximize the size of a subset that results in a non-zero bitwise AND.

Problem Statement

Given an array of positive integers nums, find the size of the largest subset such that the bitwise AND of all elements in the subset is greater than 0.

Two integers a and b have a bitwise AND greater than 0 if there exists at least one bit position k (where 0 <= k < 31) such that both a and b have a 1 at that position. Since we want the AND of the entire subset to be positive, all elements in your chosen subset must share at least one common bit set to 1 at the same position k.

Function Signature

def largest_subset_bitwise_and(nums: list[int]) -> int:

Examples

Example 1: Input: nums = [1, 2, 3, 4] Output: 2 Explanation: The binary representations are 001, 010, 011, 100. If we pick the bit at position 0, elements 1 and 3 share it (AND = 1). If we pick position 1, elements 2 and 3 share it (AND = 2). Max size is 2.

Example 2: Input: nums = [16, 17, 18, 19] Output: 4 Explanation: All numbers share the bit at position 4 (value 16). The AND of the entire set is 16, which is > 0.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9

Edge Cases

  • Array with a single element.
  • Array where no two numbers share a bit (the answer should be 1).

Hints

Hint 1

A subset has a positive bitwise AND if and only if there exists at least one bit position 'k' that is set to 1 in every element of that subset.

Hint 2

Instead of looking at combinations, count how many numbers in the array have the bit at position 'k' set for each 'k' from 0 to 30.

Hint 3

The maximum subset size will simply be the maximum frequency count among all 31 bit positions.

Follow-up questions

  • How would you return the actual elements of the subset instead of just the size?
  • If the requirement changed to finding a subset where the AND result is at least 'K', how would your approach change?
  • What is the time and space complexity of your solution, and can you optimize it for very large arrays?