0:00 / 0:00

Every number appears twice except two. XOR everything to get a XOR b, take its lowest set bit to split the numbers into two lanes, and XOR each lane to find the two loners, in O(n) time and O(1) space.

▼

The problem

LeetCode 260 (Medium). In nums every element appears exactly twice except two elements that appear once; return those two, in any order, in O(n) time and O(1) extra space.

Examples (LeetCode's): [1,2,1,3,2,5] → [3,5] (the walkthrough example); [-1,0] → [-1,0]; [0,1] → [1,0] (both checked, not shown).

TRY IT ON LEETCODE ▶

The solution

def singleNumber(nums):
    x = 0
    for n in nums:
        x ^= n
    low = x & -x
    a = b = 0
    for n in nums:
        if n & low:
            a ^= n
        else:
            b ^= n
    return [a, b]

Transcript

Single Number Three. Every number appears twice, except two that appear just once. Find those two loners, in linear time and constant extra space.

Take one, two, one, three, two, five. The ones pair up, and so do the twos. Three and five have no twin, so the answer is three and five.

The easy way counts each number in a hash map and keeps the ones seen once. That's linear time, but the map grows with the list.

Recall from Single Number: a number XOR its twin is zero. So XOR the whole list. Every pair cancels, and what's left is three XOR five. Three is zero, one, one. Five is one, zero, one. XOR marks each place they differ: one, one, zero. That's six.

But six is both loners mixed together. How do we pull them apart? Six isn't zero, so three and five differ in at least one bit. Take the lowest one. The total AND its negative keeps only that bit: here, two.

Now send every number down one of two lanes by that bit. Twins share every bit, so they always land in the same lane, and they still cancel. Three and five must split up. XOR each lane, and each leaves one loner.

In code, XOR all the numbers into one total. Keep its lowest set bit. Loop again: numbers with that bit go into lane A, the rest into lane B. Return both lanes.

Let's run it with the bit two. One has no two bit: lane B. Two: lane A. One: lane B. Three: lane A. Two: lane A. Five: lane B. Lane A holds two, three, two, which leaves three. Lane B holds one, one, five, which leaves five.

Two passes over the list: linear time. Just the total, the bit and two lanes, however long the list: constant space.

XOR everything, split on a bit where they differ, XOR each lane. That's Single Number Three.