[LeetCode] Count Triplets That Can Form Two Arrays of Equal XOR

1442. Count Triplets That Can Form Two Arrays of Equal XOR

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int countTriplets(vector<int>& A) {
A.insert(A.begin(), 0);
int res = 0, n = A.size();
for(int i = 1; i < n; i++) {
A[i] ^= A[i-1];
}
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(A[i] == A[j]) res += j - i - 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/19/PS/LeetCode/count-triplets-that-can-form-two-arrays-of-equal-xor/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.