Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. XOR every value together with a running XOR . A value XORed with itself cancels to 0, so every pair vanishes and only the lone value survives.
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- -3 × 104 ≤ numsi ≤ 3 × 104
- Each element appears twice except for one element which appears once
Example
nums = [4, 1, 2, 1, 2]4Explanation 1 and 2 each appear twice and cancel out under XOR, leaving 4.
In plain terms
- XOR
- The ^ operator: a bit comes out 1 only when its two input bits differ. XOR-ing a value with itself always gives 0, and XOR-ing anything with 0 leaves it unchanged — that's why pairs cancel out.
XOR every value into one running result
result starts at 0. XOR in nums[0] = 4.
What happens in this step
0 ^ 4
0 = 00000000
4 = 00000100
--------
00000100 = 4
XOR-ing with 0 never changes anything — result becomes 4.Steps to visualize
- Start a running result at 0.
- XOR the running result with each value in nums, in order.
- A value that has already appeared once cancels itself out, leaving 0 for that pair.
- After the last value, whatever remains is the single number.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
result starts at 0. XOR in nums[0] = 4.
What happens in this step
0 ^ 4
0 = 00000000
4 = 00000100
--------
00000100 = 4
XOR-ing with 0 never changes anything — result becomes 4.Solution
function singleNumber(nums) {
let result = 0;
for (const num of nums) {
result ^= num;
}
return result;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [4, 1, 2, 1, 2] | 4 | example from the docstring |
nums = [7] | 7 | smallest valid input, one element and no pairs |
nums = [-1, -1, -2] | -2 | negative values still cancel correctly under XOR |
nums = [2, 1, 1] | 2 | the unique value appears first in the array |
nums = [0, 1, 0] | 1 | zero itself appears as a paired value |
nums = [5, 3, 9, 3, 5, 9, 8] | 8 | several pairs before the single value |