While the hash-based approach (using a frequency map or set) is intuitive, the constraint of O(1) space suggests using Bit Manipulation (XOR).
Property of XOR: a ^ a = 0 and a ^ 0 = a.
- Initialize
res = 0. - For every
numinnums:res ^= num.
- Return
res.
- Time Complexity: O(N).
- Space Complexity: O(1).
def single_number(nums):
res = 0
for n in nums:
res ^= n
return res