forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Triplets That Can Form Two Arrays of Equal XOR.cpp
50 lines (45 loc) · 1.28 KB
/
Count Triplets That Can Form Two Arrays of Equal XOR.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class TrieNode {
public:
int numOfIndex;
int sumOfIndex;
TrieNode* child[2];
TrieNode() : numOfIndex(0), sumOfIndex(0) {
child[0] = NULL;
child[1] = NULL;
}
};
class Solution {
public:
void addNumber(TrieNode* root, int num, int idx){
for( int i = 31; i >= 0; i--){
int bit = 1 & (num >> i) ;
if ( root->child[bit] == NULL){
root->child[bit] = new TrieNode();
}
root = root->child[bit];
}
root->sumOfIndex += idx;
root->numOfIndex++;
}
int calculateIndexPair(TrieNode* root, int num, int idx){
for( int i = 31; i >= 0; i--){
int bit = 1 & (num >> i);
if (root->child[bit] == NULL){
return 0;
}
root = root->child[bit];
}
return (((root->numOfIndex) * idx) - (root->sumOfIndex));
}
int countTriplets(vector<int>& arr) {
long long ans=0;
int XOR = 0;
TrieNode* root = new TrieNode();
for ( int i = 0 ; i < arr.size(); i++){
addNumber(root, XOR, i);
XOR ^= arr[i];
ans = (ans + calculateIndexPair(root, XOR, i)) % 1000000007;
}
return ans;
}
};