Easybit-manipulation
Single Number
Problem (restated)
Every element appears twice except one. Find the single one.
Intuition
a⊕a=0, a⊕0=a; fold XOR cancels pairs.
Approaches
XOR fold
UnverifiedTime O(n)Space O(1)
Idea. x = 0; for v in nums: x ^= v.
Walkthrough. [4,1,2,1,2] → 4.
Trade-offs. O(1) space vs hash set O(n).
Solution
export function singleNumber(nums: number[]): number {
let x = 0;
for (const v of nums) x ^= v;
return x;
}
export function singleNumber(nums: number[]): number {
let x = 0;
for (const v of nums) x ^= v;
return x;
}
Template connection
Bit XOR identity.
Reflection
- XOR is associative.
a ^ a = 0anda ^ 0 = a. Pairs cancel and the single number remains. - Order does not matter. One element is itself. 0 is the identity.
- Two numbers that appear once would leave their XOR mixed. This problem promises exactly one.