Example 1
- Input
- nums = [2, 2, 1]
- Output
- 1
The value 2 appears twice and cancels out, leaving 1 as the single number.
Find the one element that appears exactly once in an array where every other element appears twice. The answer must come from a single linear pass using only constant extra space.
Given a non-empty array of integers nums, every element appears twice except for one element that appears once. Return that single element.
The solution must run in linear time and use only constant extra space, which rules out sorting the array or counting frequencies with a hash map.
The value 2 appears twice and cancels out, leaving 1 as the single number.
Both 1 and 2 appear twice, so the unpaired value 4 is the answer.
With only one element, it is trivially the single number.
The separated negative pair -2 cancels, as does the pair 3. Zero occurs once, so returning 0 is a real answer rather than evidence that no value was found.
Think of each duplicate as a pair that should disappear. In [2, 2, 1], removing the two copies of 2 leaves 1. A set can remember which values still need a partner, but XOR performs the same cancellation directly on bits: equal bits XOR to zero, and zero XOR a bit keeps that bit. Because XOR can be regrouped, the two copies need not be adjacent.
Reveal Hash Set Tracking: intuition, complexity, and code
a ^ a is 0 and a ^ 0 is a, so xoring the whole array leaves only the unpaired value.When pairs cancel, look for an operation that is its own inverse: folding the input with xor erases duplicates without storing them.