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).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!

3 Comments

  1. Miguel Gimenez November 10, 2021
    • Dan Avramescu February 2, 2022
  2. Rob November 19, 2022

Leave a Reply