XOR tricks and bitmasks
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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).
- Hand trace of Single Number on
[4, 1, 2, 1, 2]: start withxor = 0. - Process
4:xor = 0 ^ 4 = 4(0100). Process1:xor = 4 ^ 1 = 5(0101). - Process
2:xor = 5 ^ 2 = 7(0111). Process second1:xor = 7 ^ 1 = 6(0110). - Process second
2:xor = 6 ^ 2 = 4(0100). All pairs cancelled;4remains. - Hand trace of Missing Number on
nums = [3, 0, 1](n = 3): start withxor = n = 3. Loop i = 0 … 2 withxor ^= 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)
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})); }}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)
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})); }}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)
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)); }}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 viax ^ x = 0, regardless of where its two copies sit in the array. - In
missingNumber, initializingxor = nums.lengthincludes the top index n, while the loop XORs indices 0 … n-1 againstnums[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.
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
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)); }}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 wheni == j. - With
xorSwap(x1, 0, 0),arr[0]andarr[0]refer to the same memory cell, so the first^=zeroes out42and the subsequent XORs compute0 ^ 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]wheni == jcomputes 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
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); }}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) == flagworks both for single-bit flags likeWRITEand combined masks likeREAD | WRITE.- Every permission update (
|=,&= ~,^=) runs in O(1) time and stores all 4 permissions inside oneint.
- 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 theWRITEbit to1without changing other bits. - Check a flag (or combination of flags):
(perms & flag) == flagreturnstrueonly when every bit inflagis present inperms. - Revoke a flag:
perms &= ~WRITE;clears theWRITEbit whether it was0or1.
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