Bit Manipulation · Pattern 3 of 6

XOR basics: cancel, compare and prefix XOR

XOR is addition without carries: x ^ x = 0, x ^ 0 = x, and order does not matter. That makes it undo itself, mark the bits where two numbers differ, and turn prefix XORs back into the original values.

3 variations · 5 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Swap or undo without extra memory
  • Count the bits where two numbers differ
  • Recover values from running XORs
  • Track odd or even counts of letters as one mask

The template

XOR Basics
int[] swapXor(int a, int b) {
    a ^= b;                                 // a holds a ^ b
    b ^= a;                                 // b ^ (a ^ b) = a
    a ^= b;                                 // (a ^ b) ^ a = b
    return new int[]{a, b};
}

int hammingDistance(int x, int y) {
    int count = 0;
    for (int d = x ^ y; d != 0; d &= d - 1) count++;   // 1s mark differing bits
    return count;
}

int[] findArray(int[] pref) {               // pref[i] = arr[0] ^ ... ^ arr[i]
    int[] arr = new int[pref.length];
    for (int i = 0; i < pref.length; i++)
        arr[i] = i == 0 ? pref[0] : pref[i] ^ pref[i - 1];   // the shared part cancels
    return arr;
}

The variations

  1. 1XOR undoes itself

    Because x ^ y ^ y = x, XOR can store two values in one slot and get either back. The same rule lets you XOR a whole sequence in one pass, like start + 2i for every i.

  2. 2Differences as bits

    x ^ y has a 1 exactly where the two numbers differ. Count those 1s with n & (n - 1) or the built-in popcount.

  3. 3Prefix XOR and parity masks

    Like prefix sums: pref[i] ^ pref[j - 1] is the XOR of a range, so neighbouring prefixes give back the original values. With one bit per letter, the XOR of a path says which letters appear an odd number of times. Two root paths with the same mask (or masks one bit apart) make a palindrome path, so count masks in a hash map.

Mistakes to avoid

  • XOR-swapping a variable with itself (the same array slot twice): the first step makes it 0 and the value is lost.
  • Mixing up XOR with OR: 1 ^ 1 is 0, not 1.
  • For letter parity masks, counting only equal masks: a palindrome may also have one odd letter, so also try each mask with one bit flipped.
Next: Missing and repeated numbers with XOR →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.