SDE & MLE Prep

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])