0:00 / 0:00

Every number appears twice except one. XOR them all together: pairs cancel to zero, and the loner is all that's left.

▼

The problem

LeetCode 136 (Easy). Every element of a non-empty list appears exactly twice except one, which appears once. Find that one in linear time using only constant extra space.

Example: [4, 1, 2, 1, 2] → 4.

def single_number(nums):
    x = 0
    for n in nums:
        x ^= n        # pairs cancel
    return x          # the single
TRY IT ON LEETCODE ▶

The solution

def single_number(nums):
    x = 0
    for n in nums:
        x ^= n        # pairs cancel
    return x          # the single

Transcript

Single Number. Every number in the list appears twice, except one. Find the number without a partner. The catch: use linear time, and only constant extra space.

Take four, one, two, one, two. The two ones pair up, and so do the twos. Four is left dancing alone, so the answer is four.

The obvious way is a coat check: a set of the numbers you've seen. When a number arrives, hang up its ticket. When its partner shows up, take the ticket back. At the end, one ticket is left: that's the answer. It's linear time, but if every first copy arrives before any partner, the rack holds half the list. The space grows with the input.

The trick is XOR, exclusive or. Write two numbers in binary, say five and three, and compare them bit by bit. Matching bits give zero, and different bits give one. So five XOR three is six.

Two rules follow. A number XOR itself is zero, because every bit matches. A number XOR zero is just itself. And XOR doesn't care about order, so each number can slide next to its partner. Every pair cancels to zero, and only the single number is left.

In code, start a variable at zero. Loop over the list and XOR each number into it. Then return it. No set, just one number.

Let's dance it out. The floor's three tiles are the bits of that variable: four, two and one. Four steps on and lights the four tile. One lights the one tile: five. Two lights the two tile: seven. Then the second one arrives, its tile goes dark, and the pair dances off: six. The second two does the same: four. Only four is still on the floor.

Each number costs one XOR, so the time is linear. The only memory is that one variable, so the extra space is constant, however long the list gets.

Pairs cancel, the single stays. That's Single Number.