fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. }
  14. }
  15.  
  16.  
  17.  
  18. class Solution {
  19. static int subarrayXor(int[] arr, int k) {
  20. int count = 0; // this will store our answer
  21. HashMap<Integer, Integer> map = new HashMap<>(); // to store prefix XOR frequencies
  22.  
  23. int prefixXor = 0; // XOR till current index
  24.  
  25. for (int i = 0; i < arr.length; i++) {
  26. // update the prefix xor
  27. prefixXor = prefixXor ^ arr[i];
  28.  
  29. // case 1: if prefix itself is equal to k
  30. if (prefixXor == k) {
  31. count = count + 1;
  32. }
  33.  
  34. // case 2: check if we have seen prefixXor ^ k before
  35. int check = prefixXor ^ k; // this is the required xor
  36. if (map.containsKey(check)) {
  37. count = count + map.get(check);
  38. }
  39.  
  40. // finally add this prefixXor into the map
  41. if (map.containsKey(prefixXor)) {
  42. int old = map.get(prefixXor);
  43. map.put(prefixXor, old + 1);
  44. } else {
  45. map.put(prefixXor, 1);
  46. }
  47. }
  48.  
  49. return count;
  50. }
  51.  
  52. public static void main(String[] args) {
  53. int[] arr = {4, 2, 2, 6, 4};
  54. int k = 6;
  55. int ans = subarrayXor(arr, k);
  56. System.out.println("Total subarrays = " + ans);
  57. }
  58. }
  59.  
Success #stdin #stdout 0.11s 54620KB
stdin
Standard input is empty
stdout
Standard output is empty