The Odd Occurrences in An Array problem is rather simple. You are asked to find the unpaired element in an array. There can be several pairs of the same element.
For this one I chose an elegant solution available for javascript easily which still kept the O(N) or O(N*log(N)) time complexity: I used an object to hold each element which is unpaired. Cycling through the array, when a pair is found, I delete the object’s property. Otherwise, I add the property to the object. At the end there will be only the unpaired property left.
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
stack = new Object();
for (let i = 0; i < A.length; i++){
if (stack.hasOwnProperty(A[i])) {
delete stack[A[i]];
} else {
stack[A[i]] = 1;
}
}
solution = Object.keys(stack).length;
return parseInt(solution);
}
See it in action here: https://app.codility.com/demo/results/trainingW6942U-R8U/
Let me know if you found a better/faster solution!
try it with this arrat [1,1,1,2] it will return 1 which is wrong
You are right, I modified the code, it should be fine now
Not sure if this was changed since you wrote that, but for me to get 100% i need to adjust it to that to return the key (7) as the example mentioned.
“the function should return 7, as explained in the example above.”
So i changed it to:
solution = Object.keys(stack)
return parseInt(solution[0]);