Bitwise XOR
Two laws — a ^ a = 0 and a ^ 0 = a — turn O(n) space solutions into O(1). Pairs cancel. Singles survive.
HashMap uses O(n) space to find one number. XOR uses O(1) space — pairs annihilate each other at the bit level.
XOR is the toggle operator: flip a bit once (on), flip it again (off). Since XOR is commutative and associative, order doesn't matter. Every number that appears twice cancels itself out. The one number that appears once — the single — is all that remains in the accumulator.
The 4 XOR Properties
Memorise all four — they appear in every XOR problem explanation.
a ^ 0 = a5 ^ 0 = 5a ^ a = 05 ^ 5 = 0a ^ b = b ^ a3 ^ 5 = 5 ^ 3(a^b)^c = a^(b^c)(1^2)^3 = 1^(2^3)The 3-Step Framework
The same three steps appear in every XOR pattern problem.
For single-number problems: initialize result=0, XOR every element. All duplicates cancel (a^a=0). The unpaired element XOR'd with 0 stays (a^0=a). Works for any count of duplicates as long as only one element is unpaired.
result = 0
for num in nums:
result ^= num
return result # O(n) time, O(1) spaceWhen two singles exist, XOR gives a^b. Since a≠b, at least one bit differs. Use rightmost_bit = xor_all & (-xor_all) to isolate the lowest set bit. This bit is 1 in exactly one of {a,b} — it partitions all numbers cleanly.
xor_all = reduce(^, nums) # a ^ b rightmost_bit = xor_all & (-xor_all) # isolate lowest bit num1 = reduce(^ for n if n & bit) num2 = reduce(^ for n if not n & bit)
Complement of n: XOR with all-ones mask of same length. Create mask = (1 << n.bit_length()) - 1. Flip image: XOR each pixel with 1 (0→1, 1→0). The mask targets only the relevant bits, leaving higher bits untouched.
# Complement mask = (1 << n.bit_length()) - 1 return n ^ mask # Flip pixel pixel ^= 1 # toggles 0↔1
Pattern Recognition
Space constraint + pairs/singles = XOR.