fork download
  1. // C++ Program to count all subarrays having
  2. // XOR of elements as given value K using Hash Map
  3. #include <iostream>
  4. #include <vector>
  5. #include <unordered_map>
  6. using namespace std;
  7.  
  8. // Function to find the count of subarrays of arr
  9. // with XOR value equals to k
  10. int subarrayXor(vector<int>& arr, int k) {
  11. int res = 0;
  12.  
  13. // Create hash map that stores number of prefix arrays
  14. // corresponding to a XOR value
  15. unordered_map<int, int> mp;
  16.  
  17. int prefXOR = 0;
  18.  
  19. for (int val : arr) {
  20.  
  21. // Find XOR of current prefix
  22. prefXOR ^= val;
  23.  
  24. // If prefXOR ^ k exist in mp then there is a subarray
  25. // ending at i with XOR equal to k
  26. res = res + mp[prefXOR ^ k];
  27.  
  28. // If this prefix subarray has XOR equal to k
  29. if (prefXOR == k)
  30. res++;
  31.  
  32. // Add the XOR of this subarray to the map
  33. mp[prefXOR]++;
  34. }
  35.  
  36. // Return total count of subarrays having XOR of
  37. // elements as given value k
  38. return res;
  39. }
  40.  
  41. int main() {
  42. vector<int> arr = { 4, 2, 2, 6, 4 };
  43. int k = 6;
  44.  
  45. cout << subarrayXor(arr, k);
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 5264KB
stdin
Standard input is empty
stdout
4