{"id":337,"date":"2020-02-23T08:04:00","date_gmt":"2020-02-23T08:04:00","guid":{"rendered":"https:\/\/danwritescode.com\/?p=337"},"modified":"2022-02-02T03:29:27","modified_gmt":"2022-02-02T03:29:27","slug":"odd-occurrences-in-an-array-codility-100-solution-in-javascript","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/odd-occurrences-in-an-array-codility-100-solution-in-javascript\/","title":{"rendered":"Odd Occurrences In An Array – Codility 100% Solution In Javascript"},"content":{"rendered":"\n
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.<\/p>\n\n\n\n
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.
<\/p>\n\n\n\n
function solution(A) {\n \/\/ write your code in JavaScript (Node.js 8.9.4)\n stack = new Object();\n for (let i = 0; i < A.length; i++){\n if (stack.hasOwnProperty(A[i])) {\n delete stack[A[i]]; \n } else {\n stack[A[i]] = 1;\n }\n }\n solution = Object.keys(stack).length;\r\n return parseInt(solution);\n}<\/code><\/pre>\n\n\n\n