Bitwise XOR

Use x ^ x = 0 to find missing and single numbers, split two unknowns by a differing bit, and solve subarray XOR problems with prefix XOR.

Intermediate 2 min readLesson 21 of 25

XOR has three properties that make whole problems collapse into one line:

  • x ^ x = 0 — equal values cancel.
  • x ^ 0 = x — zero is the identity.
  • XOR is commutative and associative — order doesn't matter.

So XOR-ing everything together cancels every value that appears an even number of times. (More bit tricks: Bit manipulation.)

031201105
030211103
031211006
5 ^ 3 = 6: a 1 wherever the bits differ
When to use this pattern
  • Every element appears twice except one (or a known even number of times).
  • Missing number in 0..n, or a duplicate when you need O(1) space.
  • Two unknown values to separate.
  • Subarray XOR queries: prefix XOR works like prefix sum.
  • Swapping or toggling without extra space, Gray codes, maximising XOR (with a binary trie).

Single number and missing number

int singleNumber(int[] nums) {
    int x = 0;
    for (int v : nums) x ^= v;           // pairs cancel, the single one remains
    return x;
}

int missingNumber(int[] nums) {          // nums holds 0..n with one missing
    int x = nums.length;
    for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
    return x;
}

Two single numbers: split by a differing bit

XOR everything to get a ^ b. It is nonzero, so a and b differ in at least one bit. Take the lowest set bit with diff & -diff, split all numbers into two groups by that bit, and XOR each group separately. Each group contains exactly one of the unknowns.

int[] singleNumberIII(int[] nums) {
    int diff = 0;
    for (int v : nums) diff ^= v;
    int bit = diff & -diff;                       // lowest bit where a and b differ
    int a = 0;
    for (int v : nums) if ((v & bit) != 0) a ^= v;
    return new int[]{a, diff ^ a};
}

Every element appears three times except one

XOR can't cancel triples. Count how many numbers have each of the 32 bits set; every count is a multiple of 3 except where the single number contributes. ans |= (count % 3) << bit. (An O(1)-state solution with ones and twos bitmasks also exists.)

Prefix XOR

Like prefix sums: with p[i] = a[0] ^ … ^ a[i-1], the XOR of a[l..r] is p[r+1] ^ p[l]. Counting subarrays with XOR equal to k uses a hash map of prefix XORs, the same way as "subarray sum equals k".

Handy identities

TrickExpression
Lowest set bitx & -x
Clear lowest set bitx & (x - 1)
Toggle bit ix ^ (1 << i)
XOR of 1..nn, 1, n + 1, 0 for n mod 4 = 0, 1, 2, 3
Gray code of ii ^ (i >> 1)
Swap a and ba ^= b; b ^= a; a ^= b; (breaks if a and b are the same variable)
Practice problems
  • Single Numbereasy
  • Missing Numbereasy
  • Find the Differenceeasy
  • Number of 1 Bitsx & (x − 1)easy
  • Counting Bitsdp[i] = dp[i >> 1] + (i & 1)easy
  • Single Number IIImedium
  • Single Number IIcount bits mod 3medium
  • XOR Queries of a Subarrayprefix XORmedium
  • Gray Codemedium
  • Maximum XOR of Two Numbers in an Arraybinary triemedium
Key takeaways
  • x ^ x = 0, x ^ 0 = x, order doesn't matter: XOR cancels pairs.
  • Two unknowns: split the array by any bit where they differ (diff & -diff).
  • Triples: count each bit modulo 3.
  • Prefix XOR gives O(1) range XOR, just like prefix sums.