Leet Code Daily 2024-05-30 - Count Triplets That Can Form Two Arrays of Equal XOR
Solution
Preffix Sum + Hash
First, let's define preffix sum under XOR operator:
Then we know, for any valid triplet (i, j, k):
We know ; so for any where , there are possible values.
Then we can hash to count them in time.
Code
class Solution {
public:
int countTriplets(vector<int>& arr) {
vector<int> s = {0};
for (const auto& a : arr) {
s.push_back(s.back() ^ a);
}
int ans = 0;
unordered_map<int, int> cnt, sum;
for (int i = 0; i < arr.size(); i++) {
ans += cnt[s[i + 1]] * i - sum[s[i + 1]];
cnt[s[i]]++;
sum[s[i]] += i;
}
return ans;
}
};