Solution: Triples with Bitwise AND Equal To Zero
Let’s solve the Triples with Bitwise AND Equal To Zero using the Bitwise Manipulation pattern.
We'll cover the following
Statement
You’re given an array of integers called nums
. Your task is to count how many triplets of indexes (i, j, k)
satisfy the condition nums[i] & nums[j] & nums[k] == 0
, where &
is the bitwise AND operator and i
j
k
nums.length
.
Constraints:
nums.length
nums[i]
Solution
The essence of this solution lies in breaking the problem into two phases. First, precompute and count all possible pairwise bitwise AND results of the array elements, storing their frequencies in a hash map. Then, check how many of these precomputed results produce zero for each number in the array when ANDed with that number. If they do, add their frequency to the total count, since each matching pair combined with the current number forms a valid triplet. This reduces the problem from a brute-force
Using the intuition above, we implement the algorithm as follows:
Create a hash map,
counts
, to store the frequency of all possible pairwise bitwise AND results from the array.Loop through all pairs of integers in the
nums
array:Compute the bitwise AND of
nums[i]
andnums[j]
and increment the frequency of this result in thecounts
map.
Initialize a variable,
result
, withto hold the total number of valid triplets whose bitwise AND equals zero. For each element
nums[i]
in the array:Iterate through each
pair in counts
:If the result of
nums[i]
ANDequals 0
, then the pair that producedcan form a valid triplet with nums[i]
.Add
(i.e., the frequency of ) to the result
.
After processing all elements, return
result
as the total number of valid triplets.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.