Single Number

easy

Given a non-empty array of integers nums, every element appears twice except for one element, which appears once. Find and return that single element.

Your solution must run in linear time and use only constant extra space.

Hints

A hash set solves it in one pass — but what does the space rule forbid?
Which operation makes two equal values annihilate each other?
XOR every element together; x ^ x = 0, so all the pairs disappear.

Common doubts

0 is XOR's identity: x ^ 0 = x. So folding every value into 0 leaves exactly the elements that didn't cancel — here, the single unpaired one.
No. XOR is commutative and associative, so the pairs cancel no matter how the values are arranged.
Yes. XOR operates on the underlying bits, so negatives are combined and cancelled just like any other value.

Interview follow-ups

Plain XOR no longer isolates the answer. You count bits modulo 3 across all positions (or track state with two accumulators) — that's the Single Number II problem.
XOR of everything gives you the XOR of the two loners. Use any set bit of that result to split the numbers into two groups and XOR each separately — Single Number III.

Fun facts

  • This same XOR-cancellation trick powers a classic swap-without-a-temp: a ^= b; b ^= a; a ^= b.
  • RAID storage uses XOR parity the same way — the 'missing' drive can be reconstructed by XORing the others.

Asked at

AmazonGoogleMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [2, 2, 1]
Output: 1
2 appears twice and cancels itself; 1 is the only unpaired value.
Example 2
Input: nums = [4, 1, 2, 1, 2]
Output: 4
1 and 2 each appear twice and cancel; 4 is left alone.
Example 3
Input: nums = [1]
Output: 1
A single element is, trivially, the unpaired one.
Constraints

- 1 <= nums.length <= 3 * 10^4 - -3 * 10^4 <= nums[i] <= 3 * 10^4 - Every element appears exactly twice except for one element which appears once.

Solve this problem →