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
Tested onlyTime 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
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?