Codility - OddOccurencesInArray - JavaScript
Codility OddOccurencesInArray problem solved in JavaScript


🧩 OddOccurrencesInArray – Explained Line by Line
The OddOccurrencesInArray problem asks to find the value that occurs an odd number of times in an array.
Each element in the array appears exactly twice, except for one unpaired element.
Example:A = [9, 3, 9, 3, 9, 7, 9] → Result: 7
function solution(A) {
const set = new Set();
for (const n of A)
set.has(n) ? set.delete(n) : set.add(n);
return [...set][0];
}
🧮 Code Breakdown
const set = new Set();
Creates an empty Set, a data structure that stores unique values.
for (const n of A)
Iterates through the array one element at a time.
set.has(n) ? set.delete(n) : set.add(n);
This single line is the entire logic condensed.
Each time we see a number:
If it’s already in the → we remove it
If it’s not in the set → we add it
At the end, only the unpaired number remains.
It’s guaranteed that exactly one element will remain.
return [...set][0];
Converts the set into an array (using the spread operator) and returns its only element.
⚡ Additional Notes
Pure set logic: add, remove, return.
Elegance: no counters, no maps, no manual loops.
Complexity: O(N) time, O(N) space, efficient and linear.
🔗 OddOccurrencesInArray from Lesson 2 - Arrays on Codility:
https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/
✨ Bonus: One-Line Solution 💀
// one-line hack — XOR cancels pairs (O(N), O(1))
const solution = A => A.reduce((acc, v) => acc ^ v, 0);
Forget loops. Forget arrays. Forget everything.
Each XOR flips bits, cancels equals, and isolates the lone survivor: the unpaired one hiding in binary chaos.
💣 It’s not magic. It’s bit-level annihilation.
🔒 Wanna see how deep the rabbit hole goes?
☕ Buy me a coffee and I’ll open the assembly gate: bit dissection, CPU flags and registers.





