Example 1
ready- Input
nums = [ 2, 2, 1 ]- Expected
1- Why
- the pair of 2s cancels, leaving 1
A badge scanner recorded every employee twice — except for one person who passed through only once. That lone record is the one you need.
Given an integer array nums, return the value that occurs once.
A few ground rules keep the signal clean:
1 <= nums.length <= 100_000nums.length is odd.-30_000 <= nums[i] <= 30_000Hints
A map from value to frequency gives you a direct solution. What memory does it need when many different values appear?
Exclusive OR (XOR) is a bitwise operation that keeps a bit when its two inputs differ. A value XORed with itself becomes zero, and zero XORed with a value returns that value.
You can regroup and reorder XOR operations without changing the result. Fold the whole array, and every duplicate pair cancels, leaving only the unpaired value.
Can you find the answer in one pass while using the same amount of extra memory no matter how large the array becomes?
Visible cases
nums = [
2,
2,
1
]1nums = [
4,
1,
2,
1,
2
]4nums = [
7
]7Interview signal
A frequency map stores each value beside the number of times it appears. Build one, then return the entry whose count is one. This follows the guarantee directly and makes a useful correctness oracle.
def single_number(nums: list[int]) -> int:
counts: dict[int, int] = {}
for value in nums:
counts[value] = counts.get(value, 0) + 1
for value, count in counts.items():
if count == 1:
return value
raise ValueError("the input has no single value")Time O(n). Space O(n) for the frequency map.
Exclusive OR (XOR) compares two integers bit by bit and sets a result bit when the input bits differ. Three identities do all the work here:
value ^ value == 0value ^ 0 == valueStart from zero and XOR every value into one accumulator. Each duplicated value cancels its partner. The only value without a partner survives.
def single_number(nums: list[int]) -> int:
answer = 0
for value in nums:
answer ^= value
return answerNegative integers need no special branch: identical bit patterns still cancel in pairs.
Time O(n). Space O(1) — one pass and one accumulator.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
1