← Questions

Largest subset with a non-zero bitwise AND

0
TeslaCoding

A coding interview question asked at Tesla. It tests bit manipulation, counting and arrays.

Given an array arr of positive integers, choose as many elements as you can so that the bitwise AND of all chosen elements is greater than 0. The chosen elements can come from anywhere in the array (they do not need to be adjacent), and each array position can be chosen at most once.

Return the number of elements in the largest such choice.

Implement:

def largest_and_subset(arr: list[int]) -> int: ...

Constraints

  • 1 <= len(arr) <= 10^5
  • 1 <= arr[i] <= 10^7

Example 1

Input:  arr = [5, 3, 6, 9]
Output: 3

5 (0101), 3 (0011) and 9 (1001) all have the lowest bit set, so 5 & 3 & 9 = 1 > 0. Adding 6 (0110) would clear that bit, and no bit is shared by all four.

Example 2

Input:  arr = [1, 2, 4, 8]
Output: 1

No two of these numbers share a set bit, so any single element is the best you can do.

Clarifying questions

  • Is a single element always a valid answer, since every value is positive?
  • Should I return the elements themselves, or only the count?
  • Are values bounded by 10^7 (so about 24 bits) for every input?

What a strong answer covers

  • Sees that an AND is non-zero exactly when every chosen element shares at least one set bit, so the best choice is all elements that have some fixed bit set.
  • Counts, for each of the 24 bit positions, how many elements have it set, and returns the largest count: O(n * 24) time, O(1) extra memory.
  • Explains why choosing by bit is optimal: any valid choice shares some bit, so it is no larger than that bit's count.
  • Tests both examples, all equal values (answer n), powers of two only (answer 1), and a single element.

Follow-ups

  • Return the elements of the largest choice.
  • The chosen elements must be contiguous.
  • Answer the question for many ranges of the array (prefix counts per bit).

Where it's asked

What it tests

bit manipulation · counting · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding