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:
1≤ nums.length
≤1000 0≤ nums[i]
≤210
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
, with0 to hold the total number of valid triplets whose bitwise AND equals zero.For each element
nums[i]
in the array:Iterate through each
key−value pair incounts
:If the result of
nums[i]
ANDkey equals0
, then the pair that producedkey can form a valid triplet withnums[i]
.Add
value (i.e., the frequency ofkey ) to theresult
.
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: