codility solution 100% odd occurrences in an array

Odd Occurrences In An Array – Codility 100% Solution In Javascript

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);
    return parseInt(solution[0]);

See it in action here:

Let me know if you found a better/faster solution!

Leave a Reply