AlgoTales · Roadmap

XOR tricks

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

XOR compares two bits and says one when they differ. A number XOR-ed with itself becomes zero, and XOR-ing the same number twice returns you to the start. Those two facts give neat tricks: finding the odd one out, swapping values, and simple scrambling.

Practical use cases

  • Web app: The one unmatched ID in a log. A payment log records a start and an end event with the same id for each transaction, but one transaction has only a start. XOR-ing all ids together cancels each pair and leaves just the unmatched id. It needs no big list in memory, even for millions of lines.
  • Web app: Finding the missing record after an import. After importing 100,000 numbered rows, one row went missing. XOR-ing all ids from 1 to 100,000 with all ids found in the database leaves exactly the missing id. This is a one-pass check that uses almost no memory.
  • System: RAID storage and light scrambling. Disk arrays store the XOR of several disks on another disk, so any one lost disk can be rebuilt by XOR-ing the rest. Simple ciphers also XOR data with a key, and XOR-ing again gives back the original. That is why the same function can both scramble and unscramble a message.

The story: The Odd Ticket Out

Kabir ran the ticket counter at the school cricket final. Each fan bought tickets in pairs, one for themselves and one for a friend, so each ticket number appeared exactly twice in his bag. But when he emptied the bag, the count was odd: one ticket had no twin. Whose was it?

Kabir started sorting the tickets and looking for the odd one out. Mira grinned. "There is a magic operation called XOR, written ^. When you XOR a number with itself it vanishes to 0. And XOR with 0 changes nothing. So just XOR all the tickets together: every pair cancels itself, whatever order you go in, and only the lonely one remains."

Kabir tried it with 4, 1, 2, 1, 2. 0 ^ 4 = 4. Then 4 ^ 1 = 5, 5 ^ 2 = 7, 7 ^ 1 = 6, 6 ^ 2 = 4. The answer was 4 and he had used no sorting, no list, no memory beyond a single running number. "That is two lines of code," Mira said.

XOR tricks are a small family of party tricks built on those two rules: finding the missing or single number, swapping two values without a spare variable, and flipping bits. Use them to impress, but also to write memory-free solutions.

How to spot this problem, and where you need it

Everything appears in pairs except one thing, or you need to undo a change exactly, and building a big set or counting table feels like too much memory and effort for the job.

Signs you need it

  • All items appear twice except one, and the task asks for the single, missing or extra value.
  • You need a reversible operation: apply it twice and you get the original back.
  • The memory limit is tight and counting occurrences in a lookup array is not allowed.

Where to use it in a project

  • Log and reconciliation tools that must find an unmatched event, record or id fast.
  • Redundancy and checks in storage, networking, and lightweight obfuscation of values in tokens.

The solution

Start a running value at zero. XOR each item into it one after another. Because equal values cancel to zero and order does not matter, every paired item disappears, and the value left is the one that has no partner. For rebuilding lost data, XOR everything that survived. One pass and one variable are enough.

Payoff: Before: a hash map of a million ids to find one orphan. After: one variable and a single pass over the log.

Explain it like I am 8

XOR is like a pair of magic socks: two identical socks together vanish. If you throw every sock in a bag and shake out the pairs, only the sock without a partner is left in your hand.

How it works, step by step

  1. Learn the rules: a ^ a = 0, a ^ 0 = a, and XOR can be done in any order.
  2. Single number: XOR every element. Pairs cancel, and the lone number remains.
  3. Missing number (0..n): XOR all indices 0..n and all elements. Everything cancels except the missing value.
  4. Swap without a temp: a ^= b; b ^= a; a ^= b;. It works, though a plain temp variable is clearer.
  5. Be careful: these tricks assume pairs or exact ranges, so check the problem's promise.

The code in four languages

PHP

<?php
// 1. The one number that appears once, while all others appear twice.
function singleNumber(array $nums): int {
    $acc = 0;
    foreach ($nums as $x) $acc ^= $x;     // pairs cancel to 0
    return $acc;
}

// 2. The missing number from 0..n (one value is absent).
function missingNumber(array $nums): int {
    $acc = count($nums);                  // start with n
    foreach ($nums as $i => $x) {
        $acc ^= $i ^ $x;                  // index and value cancel when present
    }
    return $acc;
}

// 3. Swap two values without a temporary variable.
function swapDemo(int $a, int $b): array {
    $a ^= $b;
    $b ^= $a;
    $a ^= $b;
    return [$a, $b];
}

echo "single: " . singleNumber([4, 1, 2, 1, 2]) . "
";     // 4
echo "missing: " . missingNumber([3, 0, 1]) . "
";          // 2
echo "swapped: " . implode(', ', swapDemo(5, 9)) . "
";    // 9, 5

JavaScript

// 1. The one number that appears once, while all others appear twice.
function singleNumber(nums) {
  let acc = 0;
  for (const x of nums) acc ^= x;         // pairs cancel to 0
  return acc;
}

// 2. The missing number from 0..n (one value is absent).
function missingNumber(nums) {
  let acc = nums.length;                  // start with n
  nums.forEach((x, i) => {
    acc ^= i ^ x;                         // index and value cancel when present
  });
  return acc;
}

// 3. Swap two values without a temporary variable.
function swapDemo(a, b) {
  a ^= b;
  b ^= a;
  a ^= b;
  return [a, b];
}

console.log("single: " + singleNumber([4, 1, 2, 1, 2]));     // 4
console.log("missing: " + missingNumber([3, 0, 1]));          // 2
console.log("swapped: " + swapDemo(5, 9).join(', '));        // 9, 5

Java

public class Main {
    // 1. The one number that appears once, while all others appear twice.
    static int singleNumber(int[] nums) {
        int acc = 0;
        for (int x : nums) acc ^= x;          // pairs cancel to 0
        return acc;
    }

    // 2. The missing number from 0..n (one value is absent).
    static int missingNumber(int[] nums) {
        int acc = nums.length;                // start with n
        for (int i = 0; i < nums.length; i++) {
            acc ^= i ^ nums[i];               // index and value cancel when present
        }
        return acc;
    }

    // 3. Swap two values without a temporary variable.
    static int[] swapDemo(int a, int b) {
        a ^= b;
        b ^= a;
        a ^= b;
        return new int[]{a, b};
    }

    public static void main(String[] args) {
        System.out.println("single: " + singleNumber(new int[]{4, 1, 2, 1, 2}));   // 4
        System.out.println("missing: " + missingNumber(new int[]{3, 0, 1}));        // 2
        int[] swapped = swapDemo(5, 9);
        System.out.println("swapped: " + swapped[0] + ", " + swapped[1]);           // 9, 5
    }
}

Go

package main

import "fmt"

// 1. The one number that appears once, while all others appear twice.
func singleNumber(nums []int) int {
	acc := 0
	for _, x := range nums {
		acc ^= x // pairs cancel to 0
	}
	return acc
}

// 2. The missing number from 0..n (one value is absent).
func missingNumber(nums []int) int {
	acc := len(nums) // start with n
	for i, x := range nums {
		acc ^= i ^ x // index and value cancel when present
	}
	return acc
}

// 3. Swap two values without a temporary variable.
func swapDemo(a, b int) (int, int) {
	a ^= b
	b ^= a
	a ^= b
	return a, b
}

func main() {
	fmt.Println("single:", singleNumber([]int{4, 1, 2, 1, 2})) // 4
	fmt.Println("missing:", missingNumber([]int{3, 0, 1}))     // 2
	a, b := swapDemo(5, 9)
	fmt.Printf("swapped: %d, %d\n", a, b) // 9, 5
}

Time: O(n) · Extra space: O(1). One pass and a single running number, where the alternatives would use sorting or a lookup table.

Watch out for

  • Using XOR to find the single number when others appear three times. Pairs cancel, triples do not.
  • Swapping a variable with itself by XOR (a ^= a gives 0), which breaks array-element swaps when both indices are the same.
  • Confusing XOR (^) with "power" or with OR.

Quick check

  1. What is 7 ^ 7?
    • 7
    • 14
    • 0
  2. In [2, 3, 2, 5, 3], which number does XOR-ing everything return?
    • 5
    • 2
    • 3
  3. a ^ 0 equals...
    • 0
    • a
    • 1