function findTwoUnique(arr) {
let xor = 0;
for (const num of arr) {
xor ^= num;
}
let setBit = xor & -xor;
let x = 0, y = 0;
for (const num of arr) {
if ((num & setBit) !== 0) {
x ^= num;
} else {
y ^= num;
}
}
return [x, y].sort((a,b) => a-b);
}
console.log(findTwoUnique([2, 3, 7, 9, 2, 3]));The code uses XOR to cancel out all repeating numbers. The remaining XOR value has bits set where the two unique numbers differ. Using the rightmost set bit, it separates numbers into two groups and XORs each group to find the unique numbers. The final result is sorted ascending.
XOR of a number with itself is zero, so pairs cancel out. The XOR of the entire array leaves XOR of the two unique numbers, which helps to separate them.
function findUnique(arr) {
let xor = 0;
for (let i = 0; i <= arr.length; i++) {
xor ^= arr[i];
}
return xor;
}
console.log(findUnique([1, 2, 1, 3, 2, 5]));No error is produced. The loop runs from i = 0 to i = arr.length (6) inclusive, so arr[6] is undefined. In JavaScript, array access beyond length returns undefined, and undefined is coerced to 0 for bitwise XOR (ToInt32(undefined) = 0). The XOR of elements is 1 ^ 2 ^ 1 ^ 3 ^ 2 ^ 5 = 6, and 6 ^ 0 = 6.
XOR of all elements is 4 ^ 1 ^ 2 ^ 1 ^ 2 ^ 5 = 4 ^ 5 = 1 (binary 0001). The rightmost set bit is bit 0. Elements with bit 0 set are 1, 1, 5, so count is 3.
function findTwoUnique(arr) {
let xor = 0;
for (const num of arr) {
xor ^= num;
}
let setBit = xor & -xor;
let x = 0, y = 0;
for (const num of arr) {
if ((num & setBit) !== 0) {
x ^= num;
} else {
y ^= num;
}
}
return [x, y].sort((a,b) => a-b);
}
console.log(findTwoUnique([-1, -2, -1, -3, -2, -4]));The code correctly finds the two unique negative numbers -4 and -3. The result is sorted ascending as [-4, -3].
