Count Triplets with Even XOR Set Bits I - Problem
Given three integer arrays a, b, and c, you need to find the number of triplets (a[i], b[j], c[k]) where the XOR of all three elements has an even number of set bits.
A set bit is a bit with value 1 in the binary representation of a number. For example, the number 5 (binary: 101) has 2 set bits, while 7 (binary: 111) has 3 set bits.
The key insight is that XOR has an even number of set bits if and only if an even number of the operands have an odd number of set bits. This is because XOR combines bits, and the parity (even/odd) of set bits follows specific rules.
Examples:
3 ⊕ 5 ⊕ 6 = 0→ 0 set bits (even) ✓1 ⊕ 2 ⊕ 4 = 7→ 3 set bits (odd) ✗2 ⊕ 3 ⊕ 1 = 0→ 0 set bits (even) ✓
Input & Output
example_1.py — Basic Case
$
Input:
a = [2, 1], b = [3, 4], c = [1, 5]
›
Output:
4
💡 Note:
Valid triplets: (2,3,1)→XOR=0(0 bits), (2,4,5)→XOR=3(2 bits), (1,3,1)→XOR=3(2 bits), (1,4,5)→XOR=0(0 bits). All have even number of set bits.
example_2.py — Single Elements
$
Input:
a = [1], b = [2], c = [3]
›
Output:
0
💡 Note:
Only triplet is (1,2,3). XOR: 1⊕2⊕3 = 0⊕3 = 3 (binary: 11), which has 2 set bits (even). Wait, this should be 1! Let me recalculate: 1⊕2⊕3 = 3⊕3 = 0, which has 0 set bits (even). Result: 1.
example_3.py — All Same
$
Input:
a = [0], b = [0], c = [0]
›
Output:
1
💡 Note:
Single triplet (0,0,0). XOR: 0⊕0⊕0 = 0, which has 0 set bits (even). This triplet is valid.
Constraints
- 1 ≤ a.length, b.length, c.length ≤ 105
- 0 ≤ a[i], b[i], c[i] ≤ 109
- The number of valid triplets will fit in a 32-bit integer
- Note: XOR of three numbers has even parity iff an even number of them have odd parity
Visualization
Tap to expand
Understanding the Visualization
1
Classify Elements
Separate each array into even-parity and odd-parity groups
2
Apply Parity Rule
Valid triplets need 0 or 2 odd-parity elements (even total)
3
Count Mathematically
Use multiplication principle instead of generating all combinations
4
Optimize
Single pass through arrays, constant-time calculations
Key Takeaway
🎯 Key Insight: XOR parity depends only on the count of odd-parity operands, enabling mathematical optimization without computing actual XOR values.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code