-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountSubArrayXor.cpp
87 lines (83 loc) · 2.17 KB
/
countSubArrayXor.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
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
#include<bits/stdc++.h>
using namespace std;
// class Solution
// {
// public:
// int countSubArrayWithXor(vector<int> arr, int target)
// {
// int n = arr.size();
// int count = 0;
// int xorVal = 0;
// for(int i = 0; i< n; i++)
// {
// for(int j = i; j< n; j++)
// {
// xorVal = 0;
// for(int k = i ; k <= j ;k++)
// {
// xorVal = xorVal ^ arr[k];
// }
// if(xorVal == target)
// {
// count++;
// }
// }
// }
// return count;
// }
// };
// this is the broute force technique whose time complexity is o(n^3) and space complexity is o(1)
// class Solution
// {
// public:
// int countSubArrayWithXor(vector<int> arr, int target)
// {
// int n = arr.size();
// int count = 0;
// int xorVal = 0;
// for(int i = 0; i< n; i++)
// {
// xorVal = 0;
// for(int j = i; j< n; j++)
// {
// xorVal = xorVal ^ arr[j];
// if(xorVal == target)
// {
// count++;
// }
// }
// }
// return count;
// }
// };
// this is the better solution whose time complexity is o(n^2). and spcace complexity is o(1).
class Solution
{
public:
int countSubArrayWithXor(vector<int> arr, int target)
{
int n = arr.size();
map<int, int> mpp;
mpp[0] = 1;
int count = 0;
int xorVal = 0;
for(int i = 0; i<n; i++)
{
xorVal = xorVal ^ arr[i];
int x = target ^ xorVal;
count += mpp[x];
mpp[xorVal]++;
}
return count;
}
};
// this is the optimal solution whose time complexity is o(n)+o(nlogn) and space complexity is o(n).
int main()
{
vector<int> v = {4,2,2,6,4};
int k = 6;
Solution s;
int a = s.countSubArrayWithXor(v, k);
cout<< a;
return 0;
}