Skip to lesson

XOR tricks and bitmasks

Bitwise XOR (^) behaves like addition modulo 2 without carries: every number is its own inverse (x ⊕ x = 0), and order does not matter. That algebra lets you cancel paired values across an entire array using a single int accumulator, while bitmasks let you pack up to 32 independent boolean flags into one integer.

Single Number and Missing Number with XOR Cancellation

A bitmask is an int whose bits act as on/off flags, for example to record which items of a small set are chosen.

Three algebraic laws make bitwise XOR (^) uniquely suited to pairing problems: identity (x ⊕ 0 = x), self-inverse (x ⊕ x = 0), and commutativity/associativity (a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b).

  1. Hand trace of Single Number on [4, 1, 2, 1, 2]: start with xor = 0.
  2. Process 4: xor = 0 ^ 4 = 4 (0100). Process 1: xor = 4 ^ 1 = 5 (0101).
  3. Process 2: xor = 5 ^ 2 = 7 (0111). Process second 1: xor = 7 ^ 1 = 6 (0110).
  4. Process second 2: xor = 6 ^ 2 = 4 (0100). All pairs cancelled; 4 remains.
  5. Hand trace of Missing Number on nums = [3, 0, 1] (n = 3): start with xor = n = 3. Loop i = 0 … 2 with xor ^= i ^ nums[i], which computes 3 ⊕ (0 ⊕ 3) ⊕ (1 ⊕ 0) ⊕ (2 ⊕ 1) = 2.

Example 1 · Brute force: look for a partner of every element (O(n²) time, O(1) space)

SingleNumberPartnerSearch.javaJava
public class SingleNumberPartnerSearch {    public static int singleNumber(int[] nums) {        for (int i = 0; i < nums.length; i++) {            boolean hasPartner = false;            for (int j = 0; j < nums.length; j++) {                if (i != j && nums[i] == nums[j]) {                    hasPartner = true;                    break;                }            }            if (!hasPartner) {                return nums[i];            }        }        return -1;    }
    public static void main(String[] args) {        System.out.println(singleNumber(new int[]{4, 1, 2, 1, 2}));        System.out.println(singleNumber(new int[]{7}));    }}
Output
4
7

What this code does

  • Each element is compared with every other element. The first one with no equal partner is the answer.
  • It needs no extra memory, but the double loop makes about n² comparisons.

Example 2 · Better: a HashSet of unpaired values (O(n) time, O(n) space)

SingleNumberHashSet.javaJava
import java.util.HashSet;import java.util.Set;
public class SingleNumberHashSet {    public static int singleNumber(int[] nums) {        Set<Integer> unpaired = new HashSet<>();        for (int x : nums) {            if (!unpaired.add(x)) {                unpaired.remove(x);            }        }        return unpaired.iterator().next();    }
    public static void main(String[] args) {        System.out.println(singleNumber(new int[]{4, 1, 2, 1, 2}));        System.out.println(singleNumber(new int[]{7}));    }}
Output
4
7

What this code does

  • A value is added when first seen and removed when its partner arrives, so only the unpaired value stays.
  • It is faster than the double loop, because every lookup takes one step on average. It still needs memory for the set.

Example 3 · Optimal: XOR everything, Single Number and Missing Number (O(n) time, O(1) space)

SingleAndMissingNumberDemo.javaJava
import java.util.Arrays;
public class SingleAndMissingNumberDemo {    public static int singleNumber(int[] nums) {        int xor = 0;        for (int num : nums) {            xor ^= num;        }        return xor;    }
    public static int missingNumber(int[] nums) {        int xor = nums.length;        for (int i = 0; i < nums.length; i++) {            xor ^= i ^ nums[i];        }        return xor;    }
    public static void main(String[] args) {        int[] paired = {4, 1, 2, 1, 2};        System.out.println("Single in " + Arrays.toString(paired) + ": " + singleNumber(paired));
        int[] m1 = {3, 0, 1};        int[] m2 = {0, 1};        System.out.println("Missing in " + Arrays.toString(m1) + ": " + missingNumber(m1));        System.out.println("Missing in " + Arrays.toString(m2) + ": " + missingNumber(m2));    }}
Output
Single in [4, 1, 2, 1, 2]: 4
Missing in [3, 0, 1]: 2
Missing in [0, 1]: 2

What this code does

  • In singleNumber, every duplicated value cancels via x ^ x = 0, regardless of where its two copies sit in the array.
  • In missingNumber, initializing xor = nums.length includes the top index n, while the loop XORs indices 0 … n-1 against nums[0 .. n-1].
  • XOR needs less memory than the set approach: equal values cancel, so one int replaces the whole set.

No matter how far apart two identical numbers sit in an array, XORing the entire sequence together cancels every pair into 0 and leaves only the unpaired value.

In the Single Number problem, every element in nums appears exactly twice except for one element that appears once. A brute-force check scans for a duplicate of each element in O(n²) time, and a HashSet uses O(n) extra memory. Initializing int xor = 0 and running xor ^= num across the array runs in O(n) time and O(1) auxiliary space. In the Missing Number problem, an array of length n contains n distinct numbers chosen from 0, 1, …, n, so exactly one number in that range is missing. If you XOR all indices 0 … n together with all array elements nums[0 .. n-1], every number present in the array appears twice (once as an index/range value, once as an array element) and cancels out, leaving the missing number.

In Missing Number, using XOR avoids the potential 32-bit int overflow of the Gauss sum formula n(n+1)/2 when n is near 10⁵, though casting the sum to long is also safe.

Swapping Without a Temp Variable — And Why You Should Not

A classic interview riddle asks how to swap two integer variables a and b without a temporary variable. Using XOR: a ^= b; b ^= a; a ^= b;.

Example 4 · Why XOR Swap Fails When Swapping an Array Element with Itself

XorSwapDangerDemo.javaJava
import java.util.Arrays;
public class XorSwapDangerDemo {    public static void xorSwap(int[] arr, int i, int j) {        arr[i] ^= arr[j];        arr[j] ^= arr[i];        arr[i] ^= arr[j];    }
    public static void tempSwap(int[] arr, int i, int j) {        int temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;    }
    public static void main(String[] args) {        int a = 5;        int b = 9;        a ^= b;        b ^= a;        a ^= b;        System.out.println("Distinct variables after XOR swap: a=" + a + ", b=" + b);
        int[] x1 = {42};        xorSwap(x1, 0, 0);        System.out.println("XOR swap with i=0, j=0 on [42]: " + Arrays.toString(x1));
        int[] x2 = {42};        tempSwap(x2, 0, 0);        System.out.println("Temp swap with i=0, j=0 on [42]: " + Arrays.toString(x2));    }}
Output
Distinct variables after XOR swap: a=9, b=5
XOR swap with i=0, j=0 on [42]: [0]
Temp swap with i=0, j=0 on [42]: [42]

What this code does

  • In partition algorithms (like Lomuto quicksort or Dutch National Flag), swap(arr, i, j) is frequently called when i == j.
  • With xorSwap(x1, 0, 0), arr[0] and arr[0] refer to the same memory cell, so the first ^= zeroes out 42 and the subsequent XORs compute 0 ^ 0 = 0.

Let the initial values be a₀ and b₀. Step 1 sets a = a₀ ⊕ b₀. Step 2 sets b = b₀ ⊕ (a₀ ⊕ b₀) = a₀. Step 3 sets a = (a₀ ⊕ b₀) ⊕ a₀ = b₀.

While worth knowing if an interviewer explicitly asks the riddle, you should never use XOR swap in production or contest code. First, if you write swap(arr, i, j) using XOR and call it with i == j (two references aliasing the same memory slot), the very first line arr[i] ^= arr[i] wipes the element to 0 permanently! Second, on modern CPUs and the JVM HotSpot JIT compiler, a standard three-line swap with int temp = a; a = b; b = temp; compiles to register renaming with zero extra memory and can execute in parallel, whereas the three XOR steps form a strict serial dependency chain.

  • Self-aliasing bug: arr[i] ^= arr[j] when i == j computes x ⊕ x = 0, destroying the value.
  • Zero readability benefit: int temp = a; a = b; b = temp; is immediately clear to every reader.
  • Slower on modern hardware: each XOR depends on the result of the previous instruction.

Real World: Flags and Permissions as Bitmasks

Instead of storing 8 separate boolean fields in an object or database row, systems software, network protocols, and Unix file modes pack independent flags into a single integer bitmask, where each flag owns one power-of-two bit position (1 << k).

Example 5 · Real World: Managing User Permissions with a Bitmask

PermissionBitmaskDemo.javaJava
public class PermissionBitmaskDemo {    public static final int READ    = 1 << 0;    public static final int WRITE   = 1 << 1;    public static final int EXECUTE = 1 << 2;    public static final int DELETE  = 1 << 3;
    public static boolean hasPermission(int perms, int flag) {        return (perms & flag) == flag;    }
    public static void main(String[] args) {        int perms = READ | WRITE;        System.out.println("Initial (READ | WRITE): " + perms            + " (hasWrite=" + hasPermission(perms, WRITE)            + ", hasDelete=" + hasPermission(perms, DELETE) + ")");
        perms |= EXECUTE;        System.out.println("After granting EXECUTE: " + perms            + " (hasExecute=" + hasPermission(perms, EXECUTE) + ")");
        perms &= ~WRITE;        System.out.println("After revoking WRITE: " + perms            + " (hasWrite=" + hasPermission(perms, WRITE) + ")");
        int firstToggle = perms ^ DELETE;        int secondToggle = firstToggle ^ DELETE;        System.out.println("After toggling DELETE twice: first=" + firstToggle + ", second=" + secondToggle);    }}
Output
Initial (READ | WRITE): 3 (hasWrite=true, hasDelete=false)
After granting EXECUTE: 7 (hasExecute=true)
After revoking WRITE: 5 (hasWrite=false)
After toggling DELETE twice: first=13, second=5

What this code does

  • (perms & flag) == flag works both for single-bit flags like WRITE and combined masks like READ | WRITE.
  • Every permission update (|=, &= ~, ^=) runs in O(1) time and stores all 4 permissions inside one int.
  • Define flags as powers of two: READ = 1 << 0 (1), WRITE = 1 << 1 (2), EXECUTE = 1 << 2 (4), DELETE = 1 << 3 (8).
  • Grant a flag: perms |= WRITE; sets the WRITE bit to 1 without changing other bits.
  • Check a flag (or combination of flags): (perms & flag) == flag returns true only when every bit in flag is present in perms.
  • Revoke a flag: perms &= ~WRITE; clears the WRITE bit whether it was 0 or 1.

Because each flag is a single set bit, the four bitwise operators become set operations on flags: bitwise OR (|) grants/adds flags, bitwise AND (&) tests whether flags are present, bitwise AND with NOT (& ~) revokes/removes flags, and bitwise XOR (^) toggles flags.

Next step

Check your understanding

10 quick questions