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. 1.Single Number
    easy
  2. 2.Missing Number
    easy
  3. 3.Find the Difference
    easy
  4. 4.Hamming Distance
    easy
  5. 5.Single Number III
    medium
  6. 6.XOR Queries of a Subarray
    medium
  7. 7.Decode XORed Array
    easy
  8. 8.Decode XORed Permutation
    medium
  9. 9.Maximum XOR of Two Numbers in an Array
    medium
  10. 10.Maximum XOR With an Element From Array
    hard
  11. 11.Count Triplets That Can Form Two Arrays of Equal XOR
    medium
  12. 12.XOR Operation in an Array
    easy
  13. 13.Bitwise XOR of All Pairings
    medium
  14. 14.Minimum Bit Flips to Convert Number
    easy
  15. 15.Find XOR Sum of All Pairs Bitwise AND
    hard

Also Important

9 more questions worth practicing.

  1. 16.Single Number II
    medium
  2. 17.XOR Beauty of Array
    medium
  3. 18.Neighboring Bitwise XOR
    medium
  4. 19.Find Original Array From Prefix XOR
    medium
  5. 20.Maximum XOR for Each Query
    medium
  6. 21.Count Pairs With XOR in a Range
    hard
  7. 22.XOR of Numbers Appearing Twice
    easy
  8. 23.XOR Range Queries
    medium
  9. 24.Nim Game / XOR Game basics
    easy

How to Think

  1. Every value appears twice except one?XOR everything (x ^ x = 0)
  2. Need find missing value?Expected XOR ^ Actual XOR = Missing
  3. Need know which bits differ?a ^ b (1s mark differing positions)
  4. Need split 2 unique numbers?XOR all + Isolate diff bit (diff = xor & -xor)
  5. 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!

Visual Memory Rule
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

1. Using XOR When Frequency != 2

Assuming XOR cancels numbers appearing 3 times (x ^ x ^ x = x, not 0!). For frequency 3, use bitwise position counting.

2. Thinking XOR Means Addition

1 ^ 1 = 0 (bit cancellation), NOT 2!

3. Confusing XOR and OR

1 | 1 = 1 (combines bits) vs 1 ^ 1 = 0 (cancels identical bits).

4. Forcing XOR Tricks

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. 1. Duplicate pairs + one unique? → XOR all (x ^ x = 0)
  2. 2. Missing number 0..N? → Expected XOR (0..N) ^ Actual array XOR
  3. 3. Find differing bits?a ^ b (1s mark differing positions)
  4. 4. Hamming distance? → Count set bits of x ^ y
  5. 5. Two unique values? → XOR all + Isolate differing bit (diffBit = xor & -xor)
  6. 6. Subarray range XOR? → Prefix XOR (rangeXOR = prefix[R+1] ^ prefix[L])
  7. 7. Maximum XOR of array pairs? → Bit Trie (choose opposite binary bit high to low)
  8. 8. Overall ComplexityO(N) time, O(1) auxiliary space

Small Rules

  1. Rule 1: Duplicate pairs cancel out: x ^ x = 0 and x ^ 0 = x.
  2. Rule 2:Order does not matter for XOR (commutative & associative: a ^ b = b ^ a).
  3. Rule 3: Even frequency count cancels to 0, odd frequency count survives.
  4. Rule 4: Two unique values are separated by isolating one set bit of their total XOR sum.
  5. Rule 5: Prefix XOR range queries require no subtraction because x ^ x = 0 self-cancels old prefixes.

Production Thinking

Bitmask Changed Flag DetectionoldState ^ newState immediately reveals exact bits that changed

Compact State DiffingDiff integer configuration states without iterating key arrays

Checksum / Parity ChecksCompute simple parity in network framing headers

RAID Storage Recovery ConceptReconstruct 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."