Single Number
Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #136
Every value in the non-empty array nums appears exactly twice, except one value that appears once. Find that value in O(n) time and O(1) extra space.
Examples
text
nums = [4, 1, 2, 1, 2] → 4
nums = [7, 3, 3] → 7
nums = [−5] → −5Hints
- A hash set works but uses O(n) space.
- What is
a ^ a? What isa ^ 0?
Approach
XOR all numbers together. Because XOR is commutative and associative, the pairs can be grouped together, and each pair cancels to 0, leaving 0 ^ single = single. Works for negative numbers too.
Complexity
Time: O(n). Space: O(1).
Python solution
def singleNumber(nums):
r = 0
for x in nums:
r ^= x
return rJavaScript solution
function singleNumber(nums) {
let r = 0;
for (const x of nums) r ^= x;
return r;
}