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.
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.)
- 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;
}from functools import reduce
from operator import xor
def single_number(nums):
return reduce(xor, nums)
def missing_number(nums):
x = len(nums)
for i, v in enumerate(nums):
x ^= i ^ v
return xconst singleNumber = (nums: number[]) => nums.reduce((x, v) => x ^ v, 0);
function missingNumber(nums: number[]): number {
let x = nums.length;
nums.forEach((v, i) => (x ^= i ^ v));
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};
}def single_number_iii(nums):
diff = 0
for v in nums:
diff ^= v
bit = diff & -diff
a = 0
for v in nums:
if v & bit:
a ^= v
return [a, diff ^ a]function singleNumberIII(nums: number[]): number[] {
const diff = nums.reduce((x, v) => x ^ v, 0);
const bit = diff & -diff;
let a = 0;
for (const v of nums) if (v & bit) a ^= v;
return [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
| Trick | Expression |
|---|---|
| Lowest set bit | x & -x |
| Clear lowest set bit | x & (x - 1) |
| Toggle bit i | x ^ (1 << i) |
| XOR of 1..n | n, 1, n + 1, 0 for n mod 4 = 0, 1, 2, 3 |
| Gray code of i | i ^ (i >> 1) |
| Swap a and b | a ^= b; b ^= a; a ^= b; (breaks if a and b are the same variable) |
- 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
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.