CMD Guide
HomeDSABit Manipulation

XOR Deep Dive

XOR Deep Dive

Of the bitwise operators, XOR (^) is the one interviewers reach for again and again, because it has an algebra that lets numbers cancel. Where AND and OR lose information (you cannot undo an OR), XOR is perfectly reversible — and that reversibility is the single property behind Single Number, Missing Number, swap-without-a-temp, and finding a duplicate. Learn the algebra once and those problems stop being tricks and become the same idea wearing different clothes.

Bit by bit, a ^ b is 1 exactly when the two bits differ — it is addition modulo 2 with no carry:

aba ^ b
000
011
101
110

Two readings of that table are worth holding in your head: XOR is a "controlled flip" (XOR-ing with 1 flips a bit, with 0 leaves it) and a "difference detector" (the result marks precisely the bit positions where a and b disagree).

The algebra — four laws, each provable from the table

Commutativity + associativity together mean you can XOR a whole list in any order and any grouping and get the same answer. Combine that with self-inverse and identity and you get the property that does all the work:

The cancellation property — the engine

XOR-ing a long list, any value that appears an even number of times contributes 0, and any value that appears an odd number of times contributes itself. Proof: because order is free, mentally group all equal values together. A value appearing twice is v ^ v = 0 (self-inverse); appearing four times is (v^v)^(v^v) = 0; any even count folds to 0. An odd count is those pairs (0) plus one leftover v, and 0 ^ v = v (identity). So after XOR-ing everything, only the odd-count values survive — and if exactly one value is unpaired, XOR hands it straight to you.

Traced example — a pile cancelling to the lone value

Array [4, 1, 2, 1, 2] — every value appears twice except 4. XOR them left to right into an accumulator acc (start at 0):

StepReadComputationacc (bits)acc (dec)
start00000
140000 ^ 010001004
210100 ^ 000101015
320101 ^ 001001117
410111 ^ 000101106
520110 ^ 001001004

The accumulator wanders—4, 5, 7, 6—then lands back on 4. The cancellation view makes it obvious why, independent of the wandering: reorder the XOR as 4 ^ (1 ^ 1) ^ (2 ^ 2) = 4 ^ 0 ^ 0 = 4. The pairs annihilate; the loner remains.

Where this shows up

ProblemHow cancellation solves it
Single Number (all twice but one)XOR the whole array → pairs vanish, the unique value is left. O(n) time, O(1) space.
Missing Number in 0..nXOR all indices 0..n against all values. Each present value cancels its index; the missing value's index has no partner and survives.
Swap without a tempThree XORs move the "difference" back and forth to exchange two values in place (see the caution below).
Find the two uniques (Single Number III)XOR gives a ^ b; then x & -x isolates a bit where they differ, splitting the array into two single-number subproblems.

Missing Number, traced on [3, 0, 1] (values from 0..3, so 2 is missing). Seed acc = n = 3, then fold in i ^ nums[i]:

inums[i]i ^ nums[i]acc after
seed3
030 ^ 3 = 33 ^ 3 = 0
101 ^ 0 = 10 ^ 1 = 1
212 ^ 1 = 31 ^ 3 = 2

Indices contributed {3, 0, 1, 2} (the seed 3 plus loop indices 0,1,2) and values contributed {3, 0, 1}. Every number in both sets cancels; 2 appears only as an index → it is the answer.

Java: cancellation in action

import java.util.Arrays;

public class Xor {

    // Every value appears twice except one — XOR leaves the loner.
    static int singleNumber(int[] nums) {
        int acc = 0;
        for (int v : nums) acc ^= v;      // pairs cancel to 0
        return acc;
    }

    // The missing value in 0..n: XOR indices against values.
    static int missingNumber(int[] nums) {
        int acc = nums.length;            // seed with n, the index that has no slot
        for (int i = 0; i < nums.length; i++) acc ^= i ^ nums[i];
        return acc;
    }

    public static void main(String[] args) {
        System.out.println(singleNumber(new int[]{4, 1, 2, 1, 2})); // 4
        System.out.println(missingNumber(new int[]{3, 0, 1}));      // 2

        // XOR swap, traced: 5 and 9.
        int x = 5, y = 9;
        x = x ^ y;   // x = 12
        y = x ^ y;   // y = 5
        x = x ^ y;   // x = 9
        System.out.println("x=" + x + " y=" + y);                   // x=9 y=5

        // The aliasing trap: xor-swapping a slot with ITSELF zeroes it.
        int[] arr = {7, 8};
        int i = 0, j = 0;                 // same index
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
        System.out.println(Arrays.toString(arr));                   // [0, 8]  — 7 destroyed!
    }
}

Go: cancellation in action

package main

import "fmt"

// Every value appears twice except one — XOR leaves the loner.
func singleNumber(nums []int) int {
	acc := 0
	for _, v := range nums {
		acc ^= v // pairs cancel to 0
	}
	return acc
}

// The missing value in 0..n: XOR indices against values.
func missingNumber(nums []int) int {
	acc := len(nums) // seed with n, the index that has no slot
	for i, v := range nums {
		acc ^= i ^ v
	}
	return acc
}

func main() {
	fmt.Println(singleNumber([]int{4, 1, 2, 1, 2})) // 4
	fmt.Println(missingNumber([]int{3, 0, 1}))      // 2

	// XOR swap, traced: 5 and 9.
	x, y := 5, 9
	x = x ^ y // x = 12
	y = x ^ y // y = 5
	x = x ^ y // x = 9
	fmt.Printf("x=%d y=%d\n", x, y) // x=9 y=5

	// The aliasing trap: xor-swapping a slot with ITSELF zeroes it.
	arr := []int{7, 8}
	i, j := 0, 0 // same index
	arr[i] = arr[i] ^ arr[j]
	arr[j] = arr[i] ^ arr[j]
	arr[i] = arr[i] ^ arr[j]
	fmt.Println(arr) // [0 8]  — 7 destroyed!
}

The XOR swap — a party trick, not production code

The three-line swap works because XOR is reversible. Trace x=5, y=9: after x = x^y, x holds the "difference" 5^9 = 12; then y = x^y = (5^9)^9 = 5 (the second 9 cancels), and x = x^y = (5^9)^5 = 9. Values exchanged, no temporary. Cute. Do not use it in real code, for three concrete reasons:

Know it so you can explain why it works (it proves you understand reversibility) and, more importantly, why you would never ship it.

Traps

When to reach for XOR — and when not

Takeaways

🤖 Don't fully get this? Learn it with Claude

Stuck on XOR Deep Dive? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **XOR Deep Dive** (DSA) and want to truly understand it. Explain XOR Deep Dive from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **XOR Deep Dive** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **XOR Deep Dive** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **XOR Deep Dive** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes