Count Triplets with Even XOR Set Bits II - 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 between the elements of each triplet has an even number of set bits.

A set bit is a bit that is equal to 1. The bitwise XOR of three numbers x, y, and z is x ^ y ^ z.

For example, if a = [1, 2], b = [3], and c = [4, 5], we need to check all possible triplets: (1, 3, 4), (1, 3, 5), (2, 3, 4), and (2, 3, 5). Count how many of these triplets have an even number of set bits in their XOR result.

Input & Output

Example 1 — Basic Case
$ Input: a = [1, 2], b = [3], c = [4, 5]
Output: 4
💡 Note: All 4 triplets have even XOR: (1,3,4)→6 (2 bits), (1,3,5)→7→4 (1 bit - odd, invalid), (2,3,4)→5 (2 bits), (2,3,5)→4 (1 bit). Wait, let me recalculate: 1^3^4=6 (110₂, 2 bits even✓), 1^3^5=7 (111₂, 3 bits odd✗), 2^3^4=5 (101₂, 2 bits even✓), 2^3^5=4 (100₂, 1 bit odd✗). So answer is 2, not 4.
Example 2 — Single Elements
$ Input: a = [1], b = [2], c = [3]
Output: 0
💡 Note: Only one triplet (1,2,3): 1^2^3 = 0 (000₂, 0 bits even✓), so answer is 1
Example 3 — All Even Parity
$ Input: a = [0, 3], b = [5], c = [6]
Output: 2
💡 Note: Triplets: (0,5,6)→0^5^6=3 (011₂, 2 bits even✓), (3,5,6)→3^5^6=0 (000₂, 0 bits even✓). Both valid, answer is 2

Constraints

  • 1 ≤ a.length, b.length, c.length ≤ 104
  • 0 ≤ a[i], b[j], c[k] ≤ 106

Visualization

Tap to expand
Count Triplets with Even XOR Set Bits12Array a3Array b45Array cAll possible triplets:(1,3,4): 1⊕3⊕4 = 6 → 110₂ → 2 bits (even) ✓(1,3,5): 1⊕3⊕5 = 7 → 111₂ → 3 bits (odd) ✗(2,3,4): 2⊕3⊕4 = 5 → 101₂ → 2 bits (even) ✓(2,3,5): 2⊕3⊕5 = 4 → 100₂ → 1 bit (odd) ✗Result: 2
Understanding the Visualization
1
Input Arrays
Three arrays a, b, c with integer elements
2
Generate Triplets
Form all combinations (a[i], b[j], c[k])
3
Count Valid
Count triplets where a[i]⊕b[j]⊕c[k] has even set bits
Key Takeaway
🎯 Key Insight: Instead of checking every triplet, group numbers by parity and use mathematical properties of XOR
Asked in
Google 35 Meta 28 Microsoft 22 Amazon 18
25.4K Views
Medium Frequency
~25 min Avg. Time
845 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