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.
Finding which number lacks a pair is easy. The constraint is what makes the problem interesting: we need O(n) time and O(1) space. That rules out sorting (O(n log n)) and hash maps (O(n) space).
The problem is about pairing. Every number has a partner except one. If we can cancel out all the pairs, only the answer remains.
nums.length <= 3 * 10^4 → An O(n^2) scan is around 9 * 10^8 comparisons in the worst case, slow enough to time out. We want O(n).-3 * 10^4 <= nums[i] <= 3 * 10^4 → Values can be negative, so index-based counting tricks won't work directly.For each element, check whether it has a duplicate somewhere else in the array. If no duplicate exists, that element is the 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 have 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].The cost here is the repeated scanning: every element triggers another pass over the array. The next approach removes that by counting occurrences in a single pass.
Instead of rescanning the array for every element, count how many times each number appears using a hash map, then return the number whose count is 1.
This trades space for time. One pass builds the frequency map, a second pass finds the element that appears once. Both passes are linear.
This uses O(n) extra space for the hash map, but the problem asks for O(1) space. The next approach cancels out paired elements without storing anything, leaving only the unpaired one.
The XOR operator has three properties that solve this problem in one pass with no extra storage:
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 = bXOR all elements together. Because order is irrelevant, the two copies of each paired number sit next to each other in effect and cancel to 0. The single number XORs with 0 and survives. For [a, a, b, b, c], the running XOR reduces to (a ^ a) ^ (b ^ b) ^ c = 0 ^ 0 ^ c = c.
result to 0.result.result holds the single number.result. No extra data structures needed.