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 | |
} |
@radityaarya ^ is a XOR operator which means if the similar ( 0 or 1) bit will occur at the same position it will produce 0 ( i.e., false ) if otherwise non similar then it will produce 1 ( i.e., true).
This is my version for this exercise
function solution(A) {
let map = {};
for(var i = 0; i < A.length; i++) {;
map[A[i]] = ++map[A[i]] || 1;
}
for(properties in map) {
if(map[properties] % 2 != 0) return parseInt(properties);
}
}
Correct solution with O(n) complexity
function solution(A) {
let map = A.reduce((map, obj) => {
map[obj] = ++map[obj] || 1
return map
}, {})
let filteredArr = Object.keys(map).filter(el => map[el] %2)
return +filteredArr[0]
}
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
would you like to explain line
result ^= element
? im not familiar with^=
operator