Last Updated: March 20, 2026
We have an array where every number shows up exactly twice, except for one number that appears only once. Our job is to find that unique number.
The straightforward part is finding which number doesn't have a pair. The tricky part is the constraint: we need O(n) time and O(1) space. That rules out sorting (O(n log n)) and hash maps (O(n) space). So we need something cleverer.
The key observation here is that this problem is fundamentally about pairing. Every number has a partner except one. If we could somehow cancel out all the pairs, we'd be left with the answer.
nums.length <= 3 * 10^4 → Even O(n^2) would be roughly 9 * 10^8 operations, which is borderline. O(n) is ideal.-3 * 10^4 <= nums[i] <= 3 * 10^4 → Values can be negative, so index-based tricks won't work directly.The most natural approach: for each element, check whether it has a duplicate somewhere else in the array. If no duplicate exists, that's our answer.
We pick each element one by one and scan the rest of the array looking for a match. If we finish scanning without finding one, we've found the single number.
nums[i], set a flag indicating no duplicate has been found.nums[j] where j != i, check if nums[i] == nums[j].nums[i].For every element, we're scanning the entire array to check for a duplicate. What if we could check whether we've seen an element before in O(1) time using a hash map?
Instead of rescanning the array for every element, we can count how many times each number appears using a hash map. Then we just find the number with a count of 1.
This trades space for time. A single pass to build the frequency map, another pass to find the element that appears once. Much better than nested loops.
A hash map gives us O(1) average-time lookups and insertions. By recording each element's frequency in a single pass, we avoid the redundant comparisons of the brute force approach. The second pass through the map (which has at most (n+1)/2 entries) quickly identifies the element with count 1.
We're using O(n) extra space for the hash map, but the problem explicitly asks for O(1) space. Is there a way to "cancel out" paired elements without storing anything, leaving only the unpaired one?
This is where bit manipulation shines. The XOR operator has three properties that make it perfect for this problem:
a ^ a = 0 (any number XOR'd with itself becomes 0)a ^ 0 = a (any number XOR'd with 0 stays the same)a ^ b ^ a = a ^ a ^ b = 0 ^ b = bSo if we XOR all elements together, every pair cancels out to 0, and we're left with just the single number. It's like magic, except it's math.
result to 0.result.result holds the single number.result. No extra data structures needed.