Skip to content
ΣDSA Patterns
Menu
Language

Bit Manipulation

Guide 1 of 6 · Path 1 of 6

PreviousNext

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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 only
Time 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