Pattern #35
XOR Tricks
Important interview questions, thinking patterns, duplicate cancellation, Single Number III bit partition, Prefix XOR queries, and Go rules.
Must Solve
15 core questions — solve these first.
- 1.Single NumberXOR all numbers: x ^ x = 0 and x ^ 0 = x. Unique number remains in O(N) time & O(1) spaceeasy
- 2.Missing NumberExpected XOR (0..N) ^ Actual array XOR = Missing numbereasy
- 3.Find the DifferenceXOR all chars of s and t: extra character remainseasy
- 4.Hamming DistanceCount set bits of x ^ y (positions where bits differ)easy
- 5.Single Number IIIXOR all = a ^ b. Isolate diffBit = xor & -xor to split into 2 groups where duplicates cancel outmedium
- 6.XOR Queries of a SubarrayPrefix XOR array: query(L, R) = pref[R+1] ^ pref[L]medium
- 7.Decode XORed ArrayReconstruct: arr[i+1] = encoded[i] ^ arr[i]easy
- 8.Decode XORed PermutationCalculate total XOR of 1..N + encoded odds to find first elementmedium
- 9.Maximum XOR of Two Numbers in an ArrayBit Trie: insert binary numbers and greedily choose opposite bit from high to lowmedium
- 10.Maximum XOR With an Element From ArrayOffline queries sorted by limit + Bit Trie insertionhard
- 11.Count Triplets That Can Form Two Arrays of Equal XORPrefix XOR array: if pref[i] == pref[k+1], all j in between work (k - i triplets)medium
- 12.XOR Operation in an ArraySimulate or math formula using n % 4 XOR patterneasy
- 13.Bitwise XOR of All PairingsParity check: A[i] appears len(B) times, B[j] appears len(A) timesmedium
- 14.Minimum Bit Flips to Convert NumberCount set bits of start ^ goaleasy
- 15.Find XOR Sum of All Pairs Bitwise ANDDistributive law: (a1 ^ a2) & (b1 ^ b2)hard
Also Important
9 more questions worth practicing.
- 16.Single Number IIBit counting: For each bit position sum % 3 gives unique bitmedium
- 17.XOR Beauty of ArrayXOR self-cancellation symmetry reduces problem to XOR of all elementsmedium
- 18.Neighboring Bitwise XORTotal XOR sum of derived array must be 0 for valid original arraymedium
- 19.Find Original Array From Prefix XORReconstruct: arr[i] = pref[i] ^ pref[i-1]medium
- 20.Maximum XOR for Each QueryCumulative XOR ^ maxBitMask ((1<<k) - 1)medium
- 21.Count Pairs With XOR in a RangeBit Trie prefix counting for values < highhard
- 22.XOR of Numbers Appearing TwiceXOR elements with frequency == 2easy
- 23.XOR Range QueriesPrefix XOR array range query calculationmedium
- 24.Nim Game / XOR Game basicsBouton theorem: Nim sum (XOR sum of pile sizes) == 0 means losing positioneasy
How to Think
- Every value appears twice except one?XOR everything (x ^ x = 0)
- Need find missing value?Expected XOR ^ Actual XOR = Missing
- Need know which bits differ?a ^ b (1s mark differing positions)
- Need split 2 unique numbers?XOR all + Isolate diff bit (diff = xor & -xor)
- Need maximum XOR?Bit Trie (choose opposite bit from high to low)
Go XOR Code Templates
Single Number I & III in Go
// Single Number I: Pairs cancel out in O(N) time & O(1) space
func singleNumber(nums []int) int {
ans := 0
for _, num := range nums {
ans ^= num
}
return ans
}
// Single Number III: Find 2 unique numbers using isolated diffBit
func singleNumberIII(nums []int) []int {
xorSum := 0
for _, n := range nums {
xorSum ^= n
}
// Isolate rightmost set bit
diffBit := xorSum & -xorSum
a, b := 0, 0
for _, n := range nums {
if (n & diffBit) == 0 {
a ^= n // Group A
} else {
b ^= n // Group B
}
}
return []int{a, b}
}👉 Total Time: O(N) | Space: O(1)
Single Number III — Split Using One Differing Bit
When two unique numbers a and b appear once and all others appear twice:
1. XORing all elements yields xorSum = a ^ b.
2. Since a != b, xorSum != 0, meaning there is at least one 1-bit position where a and b differ.
3. We isolate this differing 1-bit using diffBit = xorSum & -xorSum and partition all numbers into two groups. Duplicates fall into the same group and cancel out, leaving a in one group and b in the other!
Prefix XOR & Subarray Range Queries
Just like Prefix Sum, Prefix XOR constructs an array where prefix[i+1] = prefix[i] ^ nums[i].
// Range XOR from index L to R in O(1) time
func rangeXOR(prefix []int, L int, R int) int {
return prefix[R+1] ^ prefix[L]
}👉 Why it works: prefix[L] appears twice and self-cancels because x ^ x = 0!
x ^ x = 0 and x ^ 0 = x
a ^ b ^ a = b (Self-cancellation)
Same pair → disappears | Odd count → survives
Expected ^ Actual = Missing Number
Range XOR [L..R] = prefix[R+1] ^ prefix[L]💡 Golden Rule: "XOR is cancellation: equal things disappear, and differences remain."
Common Interview Mistakes
Assuming XOR cancels numbers appearing 3 times (x ^ x ^ x = x, not 0!). For frequency 3, use bitwise position counting.
1 ^ 1 = 0 (bit cancellation), NOT 2!
1 | 1 = 1 (combines bits) vs 1 ^ 1 = 0 (cancels identical bits).
Trying to use XOR on complex frequency structures when a simple Hash Map is much clearer and less prone to edge-case bugs.
Interview Rules
- 1. Duplicate pairs + one unique? → XOR all (
x ^ x = 0) - 2. Missing number 0..N? → Expected XOR (0..N) ^ Actual array XOR
- 3. Find differing bits? →
a ^ b(1s mark differing positions) - 4. Hamming distance? → Count set bits of
x ^ y - 5. Two unique values? → XOR all + Isolate differing bit (
diffBit = xor & -xor) - 6. Subarray range XOR? → Prefix XOR (
rangeXOR = prefix[R+1] ^ prefix[L]) - 7. Maximum XOR of array pairs? → Bit Trie (choose opposite binary bit high to low)
- 8. Overall Complexity →
O(N)time,O(1)auxiliary space
Small Rules
- Rule 1: Duplicate pairs cancel out: x ^ x = 0 and x ^ 0 = x.
- Rule 2:Order does not matter for XOR (commutative & associative: a ^ b = b ^ a).
- Rule 3: Even frequency count cancels to 0, odd frequency count survives.
- Rule 4: Two unique values are separated by isolating one set bit of their total XOR sum.
- Rule 5: Prefix XOR range queries require no subtraction because x ^ x = 0 self-cancels old prefixes.
Production Thinking
Bitmask Changed Flag Detection → oldState ^ newState immediately reveals exact bits that changed
Compact State Diffing → Diff integer configuration states without iterating key arrays
Checksum / Parity Checks → Compute simple parity in network framing headers
RAID Storage Recovery Concept → Reconstruct lost drive data: A ^ B = parity $\implies$ parity ^ A = B
Remember This
x ^ x → 0
x ^ 0 → x
Same pair → disappears
Odd occurrence → survives
Different bits → XOR gives 1
Missing value → Expected ^ Actual
Two unique → XOR + split by bit
Range XOR → Prefix XOR
Maximum XOR → Bit Trie💡 Golden Rule: "XOR is cancellation: equal things disappear, and differences remain."