Given an integer array nums, return the number of AND triples. An AND triple is a triple of indices (i, j, k) such that nums[i] & nums[j] & nums[k] == 0, where & is the bitwise AND operator.
The indices do not have to be distinct, and order matters: two triples are different whenever they differ in any position, so (0, 1, 2) and (1, 0, 2) are counted separately.
Function Signature
def count_and_triples(nums: list[int]) -> int:
Rules
-
Each of
i
,
j
and
k
ranges over
0
to
len(nums) - 1
independently, so an index may repeat inside a triple, as in
(0, 0, 1)
.
-
Triples are ordered. The same indices in a different order count as another triple.
-
Return the total count as an integer.
Constraints
-
1 <= len(nums) <= 1000
-
0 <= nums[i] < 65536
(every value fits in 16 bits)
Examples
Input: nums = [2, 1, 3]
Output: 12
A triple fails only when all three chosen values share a set bit. Bit 0 is set in 1 and 3, giving 8 failing triples drawn from indices 1 and 2; bit 1 is set in 2 and 3, giving 8 failing triples drawn from indices 0 and 2; the triple (2, 2, 2) is in both groups, so 8 + 8 - 1 = 15 of the 27 triples fail and 12 remain.
Input: nums = [0, 0, 0]
Output: 27
Every value is 0, so all 3 * 3 * 3 = 27 ordered triples have an AND of 0.
Input: nums = [1, 2]
Output: 6
Since 1 & 2 is 0, any triple that uses both indices works. Only (0, 0, 0) (AND 1) and (1, 1, 1) (AND 2) fail, leaving 8 - 2 = 6.