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: XOR Equal Arrays INPUT arr = [2, 3, 1, 6, 7] 2 i=0 3 i=1 1 i=2 6 i=3 7 i=4 Find triplets (i, j, k): a = arr[i]^...^arr[j-1] b = arr[j]^...^arr[k] where a == b a segment b segment [i...j-1] and [j...k] Example Triplet: i=0, j=1, k=2 a=2, b=3^1=2 [OK] ALGORITHM STEPS 1 Key Math Insight If a==b, then a^b=0 So arr[i]^...^arr[k]=0 2 Use Prefix XOR pre[i] = arr[0]^...^arr[i-1] XOR(i,k) = pre[i]^pre[k+1] 3 Find Zero XOR Ranges If pre[i]==pre[k+1] Then XOR(i,k)=0 4 Count Valid j Values For range [i,k], j can be any of i+1,i+2,...,k That's (k-i) choices Prefix XOR Array: idx: 0 1 2 3 4 5 pre: 0 2 1 0 6 1 pre[0]=pre[3]=0 --> (i,k)=(0,2) pre[2]=pre[5]=1 --> (i,k)=(2,4) pre[0]=pre[3]=0 --> j choices: 2 FINAL RESULT Valid Triplets Found: (0, 1, 2) a=2, b=2 (0, 2, 2) a=1, b=1 (2, 3, 4) a=1, b=1 (2, 4, 4) a=7, b=7 OUTPUT 4 Verification: All 4 triplets satisfy a==b [OK] Result confirmed! Key Insight: If a == b, then a XOR b = 0, meaning the entire subarray arr[i...k] XORs to zero. Using prefix XOR, we find all pairs (i, k+1) where prefix[i] == prefix[k+1]. For each such range, any j in (i, k] works, giving (k - i) valid triplets. Time: O(n^2) or O(n) with hashmap. TutorialsPoint - Count Triplets That Can Form Two Arrays of Equal XOR | Mathematical Insight Approach
Asked in
Amazon 15 Microsoft 12 Apple 8 Google 6
89.3K 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