Count Triplets With Equal XOR Subarrays
You are given an integer array arr of length n.
Choose three indices i, j, and k such that: 0 <= i < j <= k < n
Define:
- a as the XOR of elements from index i to j - 1
- b as the XOR of elements from index j to k
In other words:
- a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
- b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Return the total number of triplets (i, j, k) such that a == b.
^ denotes the bitwise XOR operation.
Example 1:
Input: arr = [2, 3, 1, 6, 7]
Output: 4
Explanation:
The valid triplets are:
- (0, 1, 2)
- (0, 2, 2)
- (2, 3, 4)
- (2, 4, 4)
So, the answer is 4.
Example 2:
Input: arr = [1, 1, 1]
Output: 2
Explanation:
For triplet (0, 1, 1)
- Left XOR = arr[0] = 1
- Right XOR = arr[1] = 1
- Equal, so this triplet is valid.
For triplet (1, 2, 2)
- Left XOR = arr[1] = 1
- Right XOR = arr[2] = 1
- Equal, so this triplet is valid.
Hence, the answer is 2.
Now Your Turn!
Pick the correct output for the given inputInput: arr = [5, 5]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= arr.length <= 300
- 1 <= arr[i] <= 108