Count Triplets with Even XOR Set Bits I Problem
#3199
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3199.
Given three integer arrays a, b, and c, return the number of triplets (a[i], b[j], c[k]), such that the bitwise XOR of the elements of each triplet has an even number of set bits.
Example 1:
Input: a = [1], b = [2], c = [3]
Output: 1
Explanation:
The only triplet is (a[0], b[0], c[0]) and their XOR is: 1 XOR 2 XOR 3 = 00_2.
Example 2:
Input: a = [1,1], b = [2,3], c = [1,5]
Output: 4
Explanation:
Consider these four triplets:
- (a[0], b[1], c[0]): 1 XOR 3 XOR 1 = 011_2
- (a[1], b[1], c[0]): 1 XOR 3 XOR 1 = 011_2
- (a[0], b[0], c[1]): 1 XOR 2 XOR 5 = 110_2
- (a[1], b[0], c[1]): 1 XOR 2 XOR 5 = 110_2
Constraints:
1 <= a.length, b.length, c.length <= 1000 <= a[i], b[i], c[i] <= 100
Solution
Approach: Parity Counting
The number of 1 bits in x ^ y ^ z has the same parity as the sum of the bit counts of x, y and z, because XOR only cancels bits in pairs.
So only the parity of each number's bit count matters. Count how many numbers in each array have an even (0) or odd (1) bit count, giving cnt1, cnt2, cnt3. Then for each choice of parities (i, j, k) whose sum is even, add cnt1[i] * cnt2[j] * cnt3[k] to the answer.
Complexity: O(n) time and O(1) extra space, where n is the array length.
from collections import Counter
class Solution:
def tripletCount(self, a: List[int], b: List[int], c: List[int]) -> int:
cnt1 = Counter(bin(x).count("1") & 1 for x in a)
cnt2 = Counter(bin(x).count("1") & 1 for x in b)
cnt3 = Counter(bin(x).count("1") & 1 for x in c)
ans = 0
for i in range(2):
for j in range(2):
for k in range(2):
if (i + j + k) & 1 ^ 1:
ans += cnt1[i] * cnt2[j] * cnt3[k]
return ans