Count Triplets That Can Form Two Arrays of Equal XOR - Problem
Given an array of integers arr, we need to find the number of valid triplets (i, j, k) where the XOR of two subarrays are equal.
More specifically, we want to select three indices i, j, and k where 0 β€ i < j β€ k < arr.length.
We define two subarrays:
- a =
arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1](XOR from index i to j-1) - b =
arr[j] ^ arr[j + 1] ^ ... ^ arr[k](XOR from index j to k)
The goal is to count how many triplets (i, j, k) satisfy the condition a == b.
Key Insight: When a == b, then a ^ b == 0, which means the XOR of the entire subarray from i to k equals zero!
Input & Output
example_1.py β Basic Case
$
Input:
arr = [2,3,1,6,7]
βΊ
Output:
4
π‘ Note:
The triplets are (0,1,4), (0,2,4), (1,2,4), (2,3,4). For example, (0,1,4): a = arr[0] = 2, b = arr[1]βarr[2]βarr[3]βarr[4] = 3β1β6β7 = 1. Since 2 β 1, this doesn't work. Let me recalculate... Actually, (0,3,4): a = 2β3β1 = 0, b = 6β7 = 1. The valid triplets are those where the entire subarray XOR equals 0.
example_2.py β All Same Elements
$
Input:
arr = [1,1,1,1,1]
βΊ
Output:
10
π‘ Note:
Since all elements are the same, many subarrays will have XOR = 0 (even length subarrays). The XOR pattern alternates: [1]=1, [1,1]=0, [1,1,1]=1, [1,1,1,1]=0, etc. This creates multiple valid triplets.
example_3.py β Single Element
$
Input:
arr = [7]
βΊ
Output:
0
π‘ Note:
With only one element, we cannot form any triplet (i,j,k) where i < j β€ k, so the answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
The Magic Scale
Our balance scale shows that when two groups have equal XOR, their combined XOR is 0
2
Prefix Strategy
We calculate running XOR from the start - this helps us quickly find any subarray XOR
3
Finding Patterns
When we see the same prefix XOR twice, we've found a zero-XOR subarray in between
4
Counting Solutions
For each zero-XOR subarray, we count how many ways to place the middle divider
Key Takeaway
π― Key Insight: By recognizing that equal XOR subarrays have combined XOR = 0, we transform the problem into finding zero-XOR subarrays, enabling an elegant O(n) solution using prefix XOR and hash maps.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array with O(1) hash map operations
β Linear Growth
Space Complexity
O(n)
Hash maps to store prefix XOR counts and index sums
β‘ Linearithmic Space
Constraints
- 1 β€ arr.length β€ 300
- 1 β€ arr[i] β€ 108
- The XOR operation (^) has the property that a ^ a = 0 and a ^ 0 = a
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code