Bitwise XOR
easy 14 minXOR compares two numbers bit by bit and outputs 1 wherever they differ.
Video lesson · Chapter 1 of 6
One tag misses its partner
Bitwise XOR
1:26Reel
Read caption
Zee finds the sole unpaired badge in five scans by tracing the ones and zeroes of a single accumulator. Equal bits cancel. Different bits shine.
How it works
Step through the idea, or press Play.
Compare bit by bit. Line up both numbers in binary; each column gives 1 if the bits differ and 0 if they match
Understand it
Start here
What XOR is
XOR, short for exclusive or, is a bitwise operation written in maths and ^ in Python, C, Java and JavaScript. It looks at two bits and answers one question: are they different? Different gives 1, the same gives 0. That is why it is often called the difference detector.
The XOR truth table
| A | B | A ⊕ B | Why |
|---|---|---|---|
| 0 | 0 | 0 | Same bits |
| 0 | 1 | 1 | Different bits |
| 1 | 0 | 1 | Different bits |
| 1 | 1 | 0 | Same bits |
Bit by bit
XOR of two whole numbers
For whole numbers, XOR applies the truth table to every column of their binary forms at once. There are no carries, so each column is independent. (If binary is new, read Number bases first.) Take : write 5 as 0101 and 3 as 0011, compare the columns, and read the answer 0110, which is 6.
5 XOR 3, column by column
Deciding one result bit
a, b = 5, 3print(bin(a), bin(b), bin(a ^ b)) # 0b101 0b11 0b110print(a ^ b) # 6print(12 ^ 10) # 1100 ^ 1010 = 0110 = 6print(7 ^ 7, 7 ^ 0) # 0 7The rules
Four properties that power every trick
Self-cancelling and identity
Commutative and associative
Its own inverse
Self-cancel
. Any value XORed with itself vanishes.
Identity
. Zero is the safe starting value.
Commutative
. Order does not matter.
Associative
. Grouping does not matter.
The magic
Why pairs cancel out
Put the four rules together. In you may move the two s next to each other, they become 0, and 0 does nothing: . The same works for any list, however the pairs are scattered.
Folding [4, 1, 2, 1, 2]
The running XOR
Pattern 1
Find the single number
Given a list where every value appears twice except one, XOR everything into one variable. It is one pass and one integer of memory, which beats the hash set on space.
def single_number(nums): result = 0 for num in nums: result ^= num return resultprint(single_number([4, 1, 2, 1, 2])) # 4print(single_number([2, 2, 1])) # 1print(single_number([-3, 7, 7])) # -3, negatives work tooThree ways to find the single number
| Approach | Time | Extra space | Note |
|---|---|---|---|
| Count with a hash map | O(n) | O(n) | Works for any repeat count |
| Sort, then scan pairs | O(n log n) | O(1) to O(n) | Changes or copies the input |
| Running XOR | O(n) | O(1) | Needs exact pairs |
Pattern 2
Find the missing number
An array of values holds every number from to except one. The full list is what should be there; nums is what is there. XOR both together: every present number appears twice and cancels, and the missing one is left alone.
Missing number in one line
Indexes against values
def missing_number(nums): n = len(nums) result = n for i, num in enumerate(nums): result ^= i ^ num return resultprint(missing_number([3, 0, 1])) # 2print(missing_number([0, 1])) # 2print(missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1])) # 8Pattern 3
Swap without a temporary variable
a = 5, b = 3
- 1
a ^= b
abecomes , a value that encodes both originals. - 2
b ^= a
bbecomes . The two s cancel. - 3
a ^= b
abecomes . The two s cancel.
Values after each XOR
Masks
Flipping and finding bits
XOR with a mask flips exactly the bits that are 1 in the mask and leaves the rest alone, because and for a single bit. That makes it the tool for toggling flags and for spotting where two numbers differ.
XOR and friends in one table
| Pattern | Code | What it does |
|---|---|---|
| Accumulate | result ^= num | Fold a list; pairs cancel |
| Swap | a ^= b; b ^= a; a ^= b | Exchange two values without a temp |
| Toggle bit k | x ^= 1 << k | Flip one bit, leave the rest |
| Isolate lowest set bit | x & -x | Keep only the rightmost 1 (12 → 4) |
| Mark lowest set bit and below | x ^ (x - 1) | Rightmost 1 and every bit under it set (12 → 7) |
| Differ test | (a ^ b) != 0 | True when a and b differ anywhere |
| Hamming distance | bin(a ^ b).count("1") | How many bit positions differ |
x ^ (x - 1) does not toggle one bit, it builds a mask of the rightmost 1 and every bit below it.flags = 0b1010flags ^= 1 << 0 # turn bit 0 onprint(bin(flags)) # 0b1011flags ^= 1 << 0 # and off againprint(bin(flags)) # 0b1010x = 12 # 0b1100print(x & -x) # 4, the lowest set bitprint(x ^ (x - 1)) # 7, that bit and everything below itprint(bin(9 ^ 14).count("1")) # 3 bits differ between 1001 and 1110Going further
Two single numbers at once
If two values appear once and the rest twice, XORing everything gives , not either value. But , so and differ in at least one bit. Pick one such bit with x & -x, split the list by that bit, and XOR each group: each group holds one single plus whole pairs.
Splitting by a differing bit
def two_singles(nums): x = 0 for num in nums: x ^= num diff = x & -x a = b = 0 for num in nums: if num & diff: a ^= num else: b ^= num return sorted([a, b])print(two_singles([1, 2, 1, 3, 2, 5])) # [3, 5]In real systems
Where XOR shows up
RAID 5 parity
Parity = . Lose one drive and XOR the rest to rebuild it.
Error detection
Parity bits, checksums and ECC memory use XOR to notice flipped bits.
Ciphers
One-time pad: message key = ciphertext; the same key decrypts. AES and ChaCha20 use XOR at their core.
Graphics
XOR drawing mode: draw a cursor or selection box once to show it, again to erase it, without saving the background.
Hashing
FNV hashing XORs in each byte; Zobrist hashing encodes chess positions as XORs of random keys.
RAID 5 recovering a lost drive
Habits
Good and bad XOR habits
Do
- Start an XOR accumulator at 0, its identity.
- Seed missing number with
nso index n takes part. - Use
a, b = b, ain production; keep the XOR swap for interviews. - Parenthesise mixed expressions:
(a ^ b) + 1.
Avoid
- Writing
x ^ 2for a square: that is XOR, not a power. - Using the pair trick when values repeat three times.
- XOR-swapping
arr[i]witharr[j]without checkingi != j. - Expecting 32-bit wraparound from Python ints without a mask.
Recap
Key takeaways
Key points
- XOR outputs 1 where bits differ and 0 where they match: same is zero, different is one.
- Four rules: , , commutative and associative.
- Together they make pairs cancel anywhere in a list, so a running XOR finds the single number in O(n) time and O(1) space.
- Missing number: leaves only the absent value.
- XOR is its own inverse: , which powers the swap, RAID parity and one-time pads.
- XOR with a mask flips chosen bits;
x & -xisolates the lowest set bit for splitting problems. - Limits: only even repeats cancel, the XOR swap fails on the same memory, and
^is never a power.