function findTwoNonRepeating(arr: number[]): [number, number] {
let xor = 0;
for (const num of arr) {
xor ^= num;
}
const 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];
}
const result = findTwoNonRepeating([2, 3, 7, 9, 2, 3]);
console.log(result.sort((a,b) => a-b));The code uses XOR to find the XOR of all elements, which results in XOR of the two unique numbers. Then it finds a set bit to separate numbers into two groups and XORs each group to find the unique numbers. The output is the two unique numbers sorted ascending.
XOR of a number with itself is zero, so pairs cancel out. XOR of zero with a number is the number itself. This property helps isolate the XOR of the two unique elements.
function findTwoUnique(arr: number[]): [number, number] {
let xor = 0;
for (let i = 0; i < arr.length; i++) {
xor ^= arr[i];
}
const 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];
}
findTwoUnique([1, 2, 1, 3, 2, 5]);The loop uses i <= arr.length which tries to access arr[arr.length], which is undefined, causing a TypeError when XORing undefined.
const arr = [4, 1, 2, 1, 2, 5]; let xor = 0; for (const num of arr) { xor ^= num; } const setBit = xor & -xor; let x = 0, y = 0; for (const num of arr) { if ((num & setBit) !== 0) { x ^= num; } else { y ^= num; } } console.log([x, y]);
The XOR of all elements is 4 ^ 5 = 1 (binary 0001). The rightmost set bit is 1. Partitioning by this bit groups numbers with that bit set and not set. XORing each group isolates 4 and 5.
Approach A uses bitwise XOR operations with O(n) time and O(1) space, making it efficient for large arrays. Other methods have higher time or space costs.
