A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
Write a function:
function solution(A, K);
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3 A[4] = 9 A[5] = 7
A[6] = 9
the function should return 7, as explained in the example above.
Write an efficient algorithm for the following assumptions:
function solution(A) {
let optimized = new Set(A);
let answer = 0;
optimized.forEach((n) => {
let cnt = 0;
for (let i = 0; i < A.length; i++) {
if (A[i] === n) cnt++;
}
if (cnt % 2 !== 0) answer = n;
});
return answer;
}
function solution(A) {
let optOut = {};
for (let i = 0; i < A.length; i++) {
if (Object.keys(optOut).includes(`${A[i]}`)) {
optOut[A[i]] += 1;
} else {
optOut[A[i]] = 1;
}
}
let answer = 0;
Object.entries(optOut).forEach(([key, value]) => {
if (value % 2 !== 0) answer = Number(key);
});
return answer;
}
function solution(A) {
let result = 0;
for (let element of A) {
// Apply Bitwise XOR to the current and next element
// e.g) 101 -> 101 = 0 / 101 -> 011 = 110 <- let a = 5; a ^= 3; console.log(a) ? 6
result ^= element;
}
return result;
}