Single Number
You're given a non-empty integer array nums in which every value appears exactly twice, except for one value that appears only once. Return that single value. Your solution must run in O(n) time and use only O(1) extra space, so you can't keep a table of counts or build a sorted copy. Values may be negative.
Examples
nums = [2,2,1] returns 1
2 appears twice and 1 appears once, so the single value is 1.
nums = [4,1,2,1,2] returns 4
1 and 2 each appear twice, even though their copies aren't next to each other. 4 is the only value without a partner.
Constraints
- 1 <= nums.length <= 3 * 10^4
- Every element appears twice except one.
Hints
Is there an operation that cancels equal pairs out and leaves the loner intact?
XOR all elements together.
Initialize result = 0 and XOR every element into it. Pairs cancel because x ^ x == 0, leaving the unique element.
Drill This: Your Approach First
Approach
XOR every element into a running result that starts at 0. XOR is commutative and associative, x ^ x = 0 and x ^ 0 = x, so the two copies of each paired value cancel wherever they sit in the array, and only the unpaired value survives. One pass, O(n) time, O(1) space.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) result ^= num;
return result;
}
}class Solution:
def singleNumber(self, nums) -> int:
result = 0
for num in nums:
result ^= num
return result