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: 2
💡 Note: 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✗). Answer is 2.
Example 2 — Single Elements
$ Input: a = [1], b = [2], c = [3]
Output: 1
💡 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 Bits II INPUT Array a: 1 2 Array b: 3 Array c: 4 5 Binary (set bits): 1=001(1) 2=010(1) 3=011(2) 4=100(1) 5=101(2) Goal: XOR with even bits ALGORITHM STEPS 1 Count Parities Count odd/even set bits a: odd=2, even=0 b: odd=0, even=1 c: odd=1, even=1 2 XOR Parity Rule odd^odd^odd = odd even parities = even 3 Valid Combinations E-E-E or O-O-E or O-E-O or E-O-O 4 Calculate Count Multiply valid groups EEE: 0*1*1 = 0 OOE: 2*0*1 = 0 OEO: 2*1*1 = 2 EOO: 0*0*1 = 0 +2 more FINAL RESULT Valid Triplets Found: (1,3,4): 1^3^4=6 bits=2 OK (1,3,5): 1^3^5=7 bits=3 (2,3,4): 2^3^4=5 bits=2 OK (2,3,5): 2^3^5=4 bits=1 OUTPUT 4 4 triplets with even XOR Key Insight: Parity Grouping Optimization XOR of numbers has even set bits iff the sum of parities (odd/even count of bits) is even. Group elements by parity, then count valid combinations: (E,E,E), (O,O,E), (O,E,O), (E,O,O). This reduces O(n*m*k) brute force to O(n+m+k) by using multiplication of group counts. TutorialsPoint - Count Triplets with Even XOR Set Bits II | Parity Grouping Approach
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