|
| 1 | +// C++ Program to count all subarrays having |
| 2 | +// XOR of elements as given value m with |
| 3 | +// O(n) time complexity. |
| 4 | +#include <bits/stdc++.h> |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// Returns count of subarrays of arr with XOR |
| 8 | +// value equals to m |
| 9 | +long long subarrayXor(int arr[], int n, int m) |
| 10 | +{ |
| 11 | + long long ans = 0; // Initialize answer to be returned |
| 12 | + |
| 13 | + // Create a prefix xor-sum array such that |
| 14 | + // xorArr[i] has value equal to XOR |
| 15 | + // of all elements in arr[0 ..... i] |
| 16 | + int* xorArr = new int[n]; |
| 17 | + |
| 18 | + // Create map that stores number of prefix array |
| 19 | + // elements corresponding to a XOR value |
| 20 | + unordered_map<int, int> mp; |
| 21 | + |
| 22 | + // Initialize first element of prefix array |
| 23 | + xorArr[0] = arr[0]; |
| 24 | + |
| 25 | + // Computing the prefix array. |
| 26 | + for (int i = 1; i < n; i++) |
| 27 | + xorArr[i] = xorArr[i - 1] ^ arr[i]; |
| 28 | + |
| 29 | + // Calculate the answer |
| 30 | + for (int i = 0; i < n; i++) { |
| 31 | + // Find XOR of current prefix with m. |
| 32 | + int tmp = m ^ xorArr[i]; |
| 33 | + |
| 34 | + // If above XOR exists in map, then there |
| 35 | + // is another previous prefix with same |
| 36 | + // XOR, i.e., there is a subarray ending |
| 37 | + // at i with XOR equal to m. |
| 38 | + ans = ans + ((long long)mp[tmp]); |
| 39 | + |
| 40 | + // If this subarray has XOR equal to m itself. |
| 41 | + if (xorArr[i] == m) |
| 42 | + ans++; |
| 43 | + |
| 44 | + // Add the XOR of this subarray to the map |
| 45 | + mp[xorArr[i]]++; |
| 46 | + } |
| 47 | + |
| 48 | + // Return total count of subarrays having XOR of |
| 49 | + // elements as given value m |
| 50 | + return ans; |
| 51 | +} |
| 52 | + |
| 53 | +// Driver program to test above function |
| 54 | +int main() |
| 55 | +{ |
| 56 | + int arr[] = { 4, 2, 2, 6, 4 }; |
| 57 | + int n = sizeof(arr) / sizeof(arr[0]); |
| 58 | + int m = 6; |
| 59 | + |
| 60 | + cout << "Number of subarrays having given XOR is " |
| 61 | + << subarrayXor(arr, n, m); |
| 62 | + return 0; |
| 63 | +} |
| 64 | + |
0 commit comments