Count Triplets with Even XOR Set Bits I - Problem

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.

A set bit is a bit that is equal to 1. The XOR operation combines three numbers: a[i] ^ b[j] ^ c[k]. Count how many bits are 1 in the result - if this count is even, include the triplet in your answer.

Input & Output

Example 1 — Basic Case
$ Input: a = [2,1], b = [3,4], c = [1,2]
Output: 4
💡 Note: All 4 triplets work: (2,3,1)→0 (even), (2,4,2)→0 (even), (1,3,2)→0 (even), (1,4,1)→4 (even)
Example 2 — Single Elements
$ Input: a = [1], b = [2], c = [3]
Output: 1
💡 Note: Only triplet is (1,2,3): 1^2^3=0, which has 0 set bits (even), so result is 1
Example 3 — All Same Parity
$ Input: a = [1,3], b = [1,3], c = [1,3]
Output: 0
💡 Note: All numbers have odd set bits. odd^odd^odd=odd, so no valid triplets

Constraints

  • 1 ≤ a.length, b.length, c.length ≤ 105
  • 0 ≤ a[i], b[i], c[i] ≤ 109

Visualization

Tap to expand
Count Triplets with Even XOR Set Bits INPUT Array a: 2 1 Array b: 3 4 Array c: 1 2 Binary (set bits): a: 2=10(1), 1=01(1) b: 3=11(2), 4=100(1) c: 1=01(1), 2=10(1) Parity Counts: a: odd=2, even=0 ALGORITHM STEPS 1 Count Parities Count odd/even set bits in each array 2 XOR Parity Rule odd XOR odd = even even XOR even = even 3 Valid Combinations EEE, EOO, OEO, OOE (even count of odds) 4 Calculate Result Sum valid combos Parity counts: a: odd=2, even=0 b: odd=1, even=1 c: odd=2, even=0 OOE: 2*1*0 = 0 OEO: 2*1*2 = 4 Total: 0+4+0+0 = 4 FINAL RESULT Valid Triplet Count 4 Valid Triplets: 1. (2,3,2): 2^3^2=3=11 2 bits - EVEN [OK] 2. (2,4,1): 2^4^1=7=111 3 bits - ODD 3. (1,3,1): 1^3^1=3=11 2 bits - EVEN [OK] 4. (1,3,2): 1^3^2=0=0 0 bits - EVEN [OK] Output: 4 Key Insight: XOR parity optimization: Instead of checking all triplets O(n*m*k), count elements by set bit parity. For XOR result to have even set bits, need even count of odd-parity elements: EEE, EOO, OEO, OOE patterns. This reduces time complexity to O(n+m+k) - just count parities and multiply valid combinations! TutorialsPoint - Count Triplets with Even XOR Set Bits I | Optimized - Count by Parity
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen