#136

Single Number

Easy XOR

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Every number appears twice except one. Find that one in linear time and constant extra space.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: everything comes in pairs except one; find the loner.

Why this works: x ^ x = 0 and x ^ 0 = x, and order doesn't matter, so XOR of everything cancels the pairs.

Example: [4, 1, 2, 1, 2]

0^4 = 44^1 = 5, 5^2 = 77^1 = 6, 6^2 = 4 → answer 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Reaching for a HashMap — it works but uses O(n) space, which the problem asks you to avoid.