-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountSubarraysXORequalsK.cpp
More file actions
99 lines (82 loc) · 1.59 KB
/
Copy pathCountSubarraysXORequalsK.cpp
File metadata and controls
99 lines (82 loc) · 1.59 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <bitset>
#include <unordered_map>
using namespace std;
void display(vector<int> &arr)
{
for (auto x : arr)
{
cout << x << ' ';
}
cout << endl;
}
int subarrayXOR1(vector<int> &arr, int k)
{
int count = 0;
int n = arr.size();
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
int XOR = 0;
// vector<int> subArr;
for (int s = i; s <= j; s++)
{
// subArr.push_back(arr[s]);
XOR = XOR ^ arr[s];
}
if (XOR == k)
{
// display(subArr);
count++;
}
}
}
return count;
}
int subarrayXOR2(vector<int> &arr, int k)
{
int n = arr.size();
int count = 0;
for (int i = 0; i < n; i++)
{
int XOR = 0;
for (int j = i; j < n; j++)
{
XOR = XOR ^ arr[j];
if (XOR == k)
{
count++;
}
}
}
return count;
}
int subarrayXOR3(vector<int> &arr, int k)
{
int n = arr.size();
int count = 0;
unordered_map<int, int> mpp;
mpp[0] = 1;
int XOR = 0;
for(int i=0; i<n; i++)
{
XOR = XOR^arr[i];
mpp[XOR]++;
int x = XOR^k;
if(mpp.find(x) != mpp.end())
{
count += mpp[x];
}
}
return count;
}
int main()
{
vector<int> arr = {4, 2, 2, 6, 4};
display(arr);
int k = 6;
int count = subarrayXOR3(arr, k);
cout << "Count : " << count;
return 0;
}