fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int[] arr = new int[]{4, 2, 2, 6, 4};
  6. int k = 6;
  7.  
  8. System.out.println(countSubarraysWithXOR(arr, k));
  9. }
  10.  
  11. public static int countSubarraysWithXOR(int[] arr, int k) {
  12.  
  13. Map<Integer, Integer> map = new HashMap<>();
  14.  
  15. // Putting a prefix XOR of 0 has occurred once initially
  16. map.put(0, 1);
  17.  
  18. int currentXOR = 0;
  19. int count = 0;
  20.  
  21. for (int num : arr) {
  22. // Update the running prefix XOR
  23. currentXOR ^= num;
  24.  
  25. // Looking for the required prefix XOR value that satisfies the property
  26. int targetXOR = currentXOR ^ k;
  27.  
  28. // If the target prefix XOR exists, add its frequency to our count
  29. if (map.containsKey(targetXOR)) {
  30. count += map.get(targetXOR);
  31. }
  32.  
  33. // Record the current prefix XOR frequency in the map
  34. map.put(currentXOR, map.getOrDefault(currentXOR, 0) + 1);
  35. }
  36.  
  37. return count;
  38. }
  39. }
  40.  
Success #stdin #stdout 0.07s 54552KB
stdin
Standard input is empty
stdout
4