Bit Manipulation · Easy
LeetCode 136: Single Number — solution
XOR every element together: pairs cancel to 0 and only the unpaired value survives. O(n) time and O(1) space.
Problem in plain words
Every value in the array appears exactly twice, except one value that appears only once. Return that lonely value, using linear time and only constant extra memory.
For example, in [8, 3, 8] the answer is 3.
Intuition
XOR has three properties that solve this instantly: x ^ x = 0, x ^ 0 = x, and it is commutative and associative, so the order of the elements does not matter. XOR the whole array together and every duplicate pair cancels itself out, leaving only the single value. A hash set would also work, but it needs O(n) memory, which the problem forbids. More XOR tricks are in the bitwise operations lesson.
Approach
- Start with
result = 0. - For every number
xin the array, setresult ^= x. - Return
result.
Dry run
Input: [4, 7, 4, 2, 7].
| Step | x | result (binary) | result |
|---|---|---|---|
| start | - | 000 | 0 |
| 1 | 4 | 100 | 4 |
| 2 | 7 | 011 | 3 |
| 3 | 4 | 111 | 7 |
| 4 | 2 | 101 | 5 |
| 5 | 7 | 010 | 2 |
The answer is 2. The intermediate values look random, but the pairs of 4 and 7 cancel by the end.
Java solution
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int x : nums) {
result ^= x; // pairs cancel, the single value remains
}
return result;
}
}Python solution
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for x in nums:
result ^= x # pairs cancel, the single value remains
return resultComplexity
| Measure | Cost | Why |
|---|---|---|
| Time | O(n) | One XOR per element. |
| Space | O(1) | A single accumulator. |
Edge cases and common mistakes
- Negative numbers: XOR works on the two's-complement bits, so negatives cancel just like positives.
- Array of one element: the loop returns that element.
- Sorting first: sorting and scanning pairs works but costs O(n log n) time.
- Using sum tricks:
2 * sum(set(nums)) - sum(nums)is correct but needs O(n) extra space for the set.
›What if the others appear three times instead of twice?
Plain XOR no longer cancels them. Count how many numbers have each of the 32 bits set and take each count modulo 3; the leftover bits form the single number (LeetCode 137).
