Approach 1Optimal▶ Animated
XOR everything
x ^ x = 0 and x ^ 0 = x, so pairs cancel and the lonely value remains.
XOR is associative and commutative. Every duplicate pair vanishes; the unique number is what is left.
Algorithm
- Start
acc = 0. - XOR each value into
acc. - Return
acc.
- Time
- O(n)
- Space
- O(1)
class Solution: def singleNumber(self, nums: list[int]) -> int: acc = 0 for x in nums: acc ^= x return acc