Triples with Bitwise AND Equal To Zero Problem
Problem
Given an integer array nums, return the number of AND triples.
An AND triple is a triple of indices (i, j, k)
such that:
0 <= i < nums.length
0 <= j < nums.length
0 <= k < nums.length
nums[i] & nums[j] & nums[k] == 0
, where&
represents the bitwise-AND operator.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Bitmask Counting with Hash Map
Intuition
To count the number of triples (i, j, k) such that nums[i] & nums[j] & nums[k] == 0, we can precompute the count of all possible pairwise ANDs, then for each number, count how many pairs can form a triple with it such that the AND is zero. This leverages the small range of possible AND results (since nums[i] <= 2^16).
Approach
- For all pairs (i, j), compute nums[i] & nums[j] and count their frequencies in a hash map.
- For each number x in nums, for all possible mask values, if x & mask == 0, add the count of mask to the answer.
- Return the total count.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2 + n*m)
, where n is the length of nums and m is the number of unique AND results (at most 2^16). - 🧺 Space complexity:
O(m)
, for the hash map.