Last active
March 30, 2022 15:59
-
-
Save k0ff33/3eb60cfb976dee0a0a969fc9f84ae145 to your computer and use it in GitHub Desktop.
Odd Occurrences In Array exercise from Codility (JavaScript/NodeJS)
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
/** | |
* Finds element without a pair in an unsorted array of integers | |
* @param {array} A | |
* @return {int} element without a pair | |
*/ | |
function solution(A) { | |
let result = 0; | |
for (let element of A) { | |
// Apply Bitwise XOR to the current and next element | |
result ^= element | |
} | |
return result | |
} | |
// ======================= | |
// SLOW | |
// ======================= | |
function slowSolution(A) { | |
// Convert the array to a map with element as a key and number of occurrences as a value | |
// Example: { '3': 2, '7': 1, '9': 4 } | |
let map = A.reduce((map, obj) => { | |
map[obj] = ++map[obj] || 1 | |
return map | |
}, {}) | |
// Then filter the map by checking if the key's value is equal to 1 | |
// Returns array with key | |
let filteredArr = Object.keys(map).filter(el => map[el] === 1) | |
return +filteredArr[0] || null | |
} |
Fast and understandable 🤯 solution.
function solution(A) {
A = A.sort();
let val = A[A.length - 1];
for (let i = 0; i < (A.length - 1) / 2; i++) {
if (A[i * 2] !== A[i * 2 + 1]) {
val = A[i * 2];
break;
}
}
return val;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@RomaSto
Just want to know how is your solution better from @Edengb? Using filter which will also going to iterate through the array. !!
And what difference you both provide from the initial solution as slowSolution?
Please elaborate either of you. Thanks