Count Triplets That Can Form Two Arrays of Equal XOR - Problem

Given an array of integers arr, we want to select three indices i, j, and k where 0 <= i < j <= k < arr.length.

Let's define a and b as follows:

  • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
  • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]

Note that ^ denotes the bitwise-xor operation.

Return the number of triplets (i, j, k) where a == b.

Input & Output

Example 1 — Basic Case
$ Input: arr = [2,3,1,6,7]
Output: 4
💡 Note: Four valid triplets: (0,1,1), (0,2,2), (2,3,4), (2,4,4). Each creates equal left and right XOR values.
Example 2 — Simple Array
$ Input: arr = [1,1,1,1]
Output: 6
💡 Note: Multiple ways to split: any subarray of even length has XOR=0, creating many valid triplets.
Example 3 — Single Element Subarrays
$ Input: arr = [2,3,1,6]
Output: 1
💡 Note: Only (2,3,3) works where left=[2,3] has XOR=1 and right=[1] has XOR=1.

Constraints

  • 1 ≤ arr.length ≤ 300
  • 1 ≤ arr[i] ≤ 108

Visualization

Tap to expand
Count Triplets with Equal XOR SubarraysFind (i,j,k) where XOR(i to j-1) = XOR(j to k)23167Left: 3Right: 13 ≠ 1 ❌Left: 2^3=1Right: 11 = 1 ✅Output: 4 valid triplets found
Understanding the Visualization
1
Input Array
Given array of integers to analyze
2
Find Splits
Look for ways to split into equal XOR parts
3
Count Valid
Return total count of valid triplets
Key Takeaway
🎯 Key Insight: Use XOR properties - if left XOR equals right XOR, then total range XOR equals 0
Asked in
Amazon 15 Microsoft 12 Apple 8 Google 6
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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