Skip to content

XOR Tricks

Lesson 2 of 5 · 4 min

XOR Tricks

Step 1 of 7

XOR folds a whole list into one accumulator. Start at zero; the first value is 4.

The Idea

XOR has two properties that do all the work: x ^ x is 0, and x ^ 0 is x. It also ignores order.

So XOR a whole list together and every value that appears twice erases itself. Whatever survives appeared an odd number of times — in O(n) time and O(1) memory.

Real-World Example

RAID 5 stores one parity drive that is the XOR of the others. Lose any single disk and its contents are rebuilt by XOR-ing everything that remains: the missing block is the value that no longer has a partner.

The Code

Your turn

Fill in the blank.

def single_number(nums):
  acc = 0
  for x in nums:
      acc = acc ___ x
  return acc

print(single_number([9, 5, 9]))   # want 5

Mini quiz

1 / 3

What is `x ^ x`?