Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #1361 of 6Next →

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

Unverified
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

Fold XOR from 0 across every value. Paired values cancel. The value that appears once remains.

Reflection

  • XOR is associative. a ^ a = 0 and a ^ 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.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Every value appears twice except one. Fold XOR: a⊕a=0, a⊕0=a.

4
0
1
1
2
2
1
3
2
4

x = 0

Key:CurrentActive rangeMatchSettledEliminated