We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We know that a number XORed with itself is 0. Instead of calculating the subarrays directly, we calculate the number of times each number appears in any subarray. If it appears an even number of times, then (x ^ x ... ^ x) where there is an even number of "x" values will give 0. If there are an odd number of "x" values, the result will be "x".
Case 1: n is even
Each element appears an even number of times throughout the subarrays, so the answer is 0.
Case 2: n is odd
We notice that the odd-indexed elements appear an even number of times throughout the subarrays, so xoring them together will give 0, so we can ignore the odd-indexed elements.
The even-indexed elements in the original subarray will appear an odd number of times throughout the subarrays. We can go ahead and XOR the values of the even-indexed elements in the original array to get our final answer.
importjava.util.Scanner;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscan=newScanner(System.in);intT=scan.nextInt();while(T-->0){intn=scan.nextInt();int[]array=newint[n];for(inti=0;i<n;i++){array[i]=scan.nextInt();}if(n%2==0){// Case 1System.out.println(0);}else{// Case 2intresult=0;for(inti=0;i<n;i++){if(i%2==0){result^=array[i];}}System.out.println(result);}}scan.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sansa and XOR
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
Time Complexity: O(n) per testcase
XOR properties:
1) x ^ x = 0
2) x ^ 0 = x
We know that a number XORed with itself is 0. Instead of calculating the subarrays directly, we calculate the number of times each number appears in any subarray. If it appears an even number of times, then (x ^ x ... ^ x) where there is an even number of "x" values will give 0. If there are an odd number of "x" values, the result will be "x".
Case 1: n is even
Each element appears an even number of times throughout the subarrays, so the answer is 0.
Case 2: n is odd
We notice that the odd-indexed elements appear an even number of times throughout the subarrays, so xoring them together will give 0, so we can ignore the odd-indexed elements.
The even-indexed elements in the original subarray will appear an odd number of times throughout the subarrays. We can go ahead and XOR the values of the even-indexed elements in the original array to get our final answer.