Bitwise XOR
easy 14 minXOR compares two numbers bit by bit and outputs 1 wherever they differ.
See it run
Fold [4, 1, 2, 1, 2] into one variable until only 4 is left, work out 5 XOR 3 one column at a time, swap two numbers with three XORs, and find the missing number in [3, 0, 1].
Operations
Find single number
Every value in [4, 1, 2, 1, 2] appears twice except one. XOR everything into one variable: pairs cancel because $a \oplus a = 0$, and the survivor is the answer. One pass, one variable.
Step 1 of 8
The problem: one value has no partner
- 40
- 11
- 22
- 13
- 24
In [4, 1, 2, 1, 2] every number appears twice except one. We want it in O(n) time and O(1) extra space, so no hash set. Start with result = 0, because XOR with 0 leaves a number unchanged.
Step 1: The problem: one value has no partner
def single_number(nums): result = 0 for num in nums: result ^= num return result- Time
- O(n)
- Space
- O(1)
- hash set
- O(n) time, O(n) space
- sort first
- O(n log n) time
If a problem says "every element appears twice except one" and asks for O(1) space, the answer is a running XOR.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Using ^ as a power operator
criticalIn Python, C, Java and JavaScript, ^ is bitwise XOR. 2 ^ 3 is 1, not 8. Powers are ** in Python and Math.pow or a loop elsewhere.
Wrongarea = side ^ 2 # XOR: 5 ^ 2 == 7Rightarea = side ** 2 # 25XOR-swapping a slot with itself
criticalWhen i == j, arri ^= arrj computes x ^ x = 0 and the value is gone. Shuffles and partition code hit this whenever both indexes coincide.
Wrongarr[i] ^= arr[j]arr[j] ^= arr[i]arr[i] ^= arr[j] # arr[i] becomes 0 when i == jRightif i != j: arr[i] ^= arr[j] arr[j] ^= arr[i] arr[i] ^= arr[j]# or simply: arr[i], arr[j] = arr[j], arr[i]Using the pair trick when duplicates come in threes
majorXOR only cancels values that appear an even number of times. In [2, 2, 3, 2] the three 2s leave a 2 behind, so the fold gives 2 ^ 3 = 1. Triples need per-bit counting modulo 3.
Wrongdef single(nums): # every other value appears 3 times r = 0 for x in nums: r ^= x return r # single([2, 2, 3, 2]) == 1Rightdef single(nums): # count each bit modulo 3 ans = 0 for k in range(32): if sum((x >> k) & 1 for x in nums) % 3: ans |= 1 << k return ans if ans < 2**31 else ans - 2**32Starting the accumulator at the wrong value
majorXOR's identity is 0, not 1. Starting at 1 flips bit 0 of the answer. In missing number, forgetting to seed with n leaves index n out of the cancellation.
Wrongresult = 1 # flips bit 0result = 0 # missing_number([0, 1]) returns 0, not 2Rightresult = 0 # single numberresult = len(nums) # missing number: include index nForgetting operator precedence
minorArithmetic and shifts bind tighter than ^ in Python, so a ^ b + 1 means a ^ (b + 1). Parenthesise mixed expressions; in C and Java, == even binds tighter than ^.
Wrongx = a ^ b + 1 # a ^ (b + 1)mask = 1 << k + 1 # 1 << (k + 1)Rightx = (a ^ b) + 1mask = (1 << k) + 1Clearing the lowest set bit when you meant to isolate it
majorx & (x - 1) removes the lowest 1 bit; x & -x keeps only that bit. Single Number III needs the isolated bit to split the array into two groups.
Wrongdiff = xor_all & (xor_all - 1) # 6 -> 4, clears the bitRightdiff = xor_all & -xor_all # 6 -> 2, isolates it
Interview tips
Spot it fast
- "Every element appears twice except one" with O(1) space.
- "Numbers 0 to n, one is missing" or "one is duplicated".
- Find where two numbers differ, or count differing bits (Hamming distance).
- Toggle a flag or a bit: x ^= 1 << k.
Properties to know cold
- Self-cancelling: a ⊕ a = 0. Identity: a ⊕ 0 = a.
- Commutative and associative: order and grouping never matter.
- Its own inverse: (a ⊕ b) ⊕ b = a.
- No carries: every bit position is independent.
Say it in the interview
- "Pairs cancel because a XOR a is 0, and order does not matter because XOR is commutative and associative."
- Compare with the hash set: same O(n) time, but O(1) instead of O(n) space.
- Mention the limits: only even repeats cancel, and the XOR swap fails on aliased memory.
Watch out
- ^ is XOR, never a power, in Python, C, Java and JavaScript.
- Parenthesise expressions that mix ^ with +, -, << or ==.
- Python ints are unbounded, so masks like & 0xFFFFFFFF are needed to mimic 32-bit results.