260. Single Number III
Problem
In nums, exactly two values appear once and every other value appears exactly twice. Return the two single values, in any order, using O(n) time and O(1) extra space.
Example: [1,2,1,3,2,5] → [3,5]
XOR all → a ^ b (non-zero). Its lowest set bit diff = x & −x is a bit where a and b differ: split numbers by that bit and XOR each group separately.
Complexity: O(n) time, O(1) space.
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
x = reduce(lambda a, b: a ^ b, nums)
diff = x & -x
a = 0
for v in nums:
if v & diff:
a ^= v
return sorted([a, x ^ a])
assert sorted(Solution().singleNumber([1, 2, 1, 3, 2, 5])) == sorted([3, 5])
assert sorted(Solution().singleNumber([-1, 0])) == sorted([-1, 0])
class Solution {
public int[] singleNumber(int[] nums) {
int x = 0;
for (int v : nums) x ^= v;
int diff = x & -x, a = 0;
for (int v : nums) if ((v & diff) != 0) a ^= v;
return new int[]{Math.min(a, x ^ a), Math.max(a, x ^ a)};
}
}
func singleNumber(nums []int) []int {
x := 0
for _, v := range nums {
x ^= v // = a ^ b
}
diff := x & -x // a bit where a and b differ splits the numbers into two groups
a := 0
for _, v := range nums {
if v&diff != 0 {
a ^= v
}
}
return []int{a, x ^ a}
}