1442. 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 and k) Where a == b.
Example 1:
Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
Example 2:
Input: arr = [1,1,1,1,1]
Output: 10
Example 3:
Input: arr = [2,3]
Output: 0
Example 4:
Input: arr = [1,3,5,7,9]
Output: 3
Example 5:
Input: arr = [7,11,12,9,5,2,7,17,22]
Output: 8
Constraints:
1 <= arr.length <= 3001 <= arr[i] <= 10^8
Problem Summary #
Given an integer array arr. You need to choose three indices i, j, and k from the array, where (0 <= i < j <= k < arr.length). a and b are defined as follows:
- a = arr[i] ^ arr[i + 1] ^ … ^ arr[j - 1]
- b = arr[j] ^ arr[j + 1] ^ … ^ arr[k]
Note: ^ represents the bitwise XOR operation. Return the number of triplets (i, j, k) that can make a == b hold.
Solution Idea #
- This problem requires using the XOR property
x^x = 0. The problem asks fora == b, which can be equivalently transformed intoarr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1] ^ arr[j] ^ arr[j + 1] ^ ... ^ arr[k] = 0. In this way, j can effectively be “ignored”, and we can focus on finding all intervals [i,k] whose XOR result is 0; these are the answer. Use the prefix sum idea, except that this problem uses XOR rather than addition. Also, by the XOR propertyx^x = 0, XORing the same part is equivalent to eliminating it, so we haveprefix[i,k] = prefix[0,k] ^ prefix[0,i-1]. Find every i, k combination withprefix[i,k] = 0, where i < j <= k. Then the number of valid triplets (i,j,k) depends entirely on the range of possible j values (because i and k are already fixed). The range of j values is k-i, so accumulate all such k-i values that satisfy the condition, and the result is the final answer.
Code #
package leetcode
func countTriplets(arr []int) int {
prefix, num, count, total := make([]int, len(arr)), 0, 0, 0
for i, v := range arr {
num ^= v
prefix[i] = num
}
for i := 0; i < len(prefix)-1; i++ {
for k := i + 1; k < len(prefix); k++ {
total = prefix[k]
if i > 0 {
total ^= prefix[i-1]
}
if total == 0 {
count += k - i
}
}
}
return count
}