Last active
October 7, 2016 06:39
-
-
Save yevgnenll/2fe9161393c5b34dd2aabdf2b6bd3d3f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.