Count Triplets with Even XOR Set Bits II Problem
#3215
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 3215.
Given three integer arrays a, b, and c, return the number of triplets (a[i], b[j], c[k]), such that the bitwise XOR between 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 <= 10^50 <= a[i], b[i], c[i] <= 10^9
Solution
Approach: Bit Manipulation
The parity of the number of 1 bits in x ^ y ^ z equals the parity of the sum of the three individual bit counts. So only the parity of each number's bit count matters.
Count, for each of a, b and c, how many numbers have an even and how many have an odd bit count. Then try all 8 parity combinations (i, j, k); whenever i + j + k is even, add cnt1[i] * cnt2[j] * cnt3[k] to the answer.
Complexity: time O(n), space O(1), where n is the length of the arrays.
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