Skip to content

Instantly share code, notes, and snippets.

@yevgnenll
Last active October 7, 2016 06:39
Show Gist options
  • Save yevgnenll/2fe9161393c5b34dd2aabdf2b6bd3d3f to your computer and use it in GitHub Desktop.
Save yevgnenll/2fe9161393c5b34dd2aabdf2b6bd3d3f to your computer and use it in GitHub Desktop.
function solution(A){
if(A.length === 1)
return A[0];
A = A.sort();
var xor = 0;
for(var i=0; i<A.length; i++){
console.log('xor' , xor^A[i], 'xor:',xor, A[i]);
xor = xor ^ A[i];
}
return xor
}
console.log(solution([9,3,9,3,7]));
@yevgnenll
Copy link
Author

yevgnenll commented Oct 7, 2016

https://codility.com/programmers/lessons/14

First, I thought how I can do this in the O(1) space complexity until I notice that there is only one element left unpaired in this problem.

If all the elements except one is paired, we can use xor for this problem and just one scanning is okay. Since A xor A = 0, and B xor 0 = B, if we keep on performing xor for all the values, the one left after iteration is the value unpaired.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment