Bit Manipulation · Pattern 4 of 6

Missing and repeated numbers with XOR

XOR everything together and every value that appears twice cancels, leaving the odd one out. Add the indexes too and the missing number is left. With two odd ones out, split by any bit where they differ.

3 variations · 3 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Every element appears twice except one (or two)
  • Numbers 0..n with exactly one missing
  • O(1) extra space is required
  • A hash set would work, but the follow-up says no extra memory

The template

Missing / Repeated Numbers
int singleNumber(int[] nums) {
    int x = 0;
    for (int v : nums) x ^= v;              // pairs cancel
    return x;
}

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

int[] twoOddNum(int[] arr) {                // the two values seen an odd number of times
    int both = 0;
    for (int v : arr) both ^= v;            // a ^ b, not 0 because a != b
    int bit = both & -both;                 // a bit where a and b differ
    int a = 0;
    for (int v : arr) if ((v & bit) != 0) a ^= v;   // XOR of one group only
    int b = both ^ a;
    return new int[]{Math.max(a, b), Math.min(a, b)};
}

The variations

  1. 1Pairs cancel

    XOR all values. Each value seen twice becomes 0, so only the single one is left. It works in any order and with O(1) memory.

  2. 2Pair values with indexes

    XOR in every index 0..n and every value. Each present number meets its own index and cancels; the missing one has no partner and stays.

  3. 3Two odd ones out: split by a bit

    The XOR of everything is a ^ b. Any set bit in it is a bit where a and b differ, so it splits all numbers into two groups with one of them in each. XOR one group to get a, then b = (a ^ b) ^ a.

Mistakes to avoid

  • Missing number: starting x at 0 instead of n, so the value n itself is never XORed in.
  • Two odd ones: testing (v & bit) == 1 instead of != 0; the bit is usually not bit 0.
  • Using the sum formula n(n + 1) / 2 for the missing number in Java or C++ with big n: it can overflow. XOR cannot.
Next: Sum over subsets (SOS) DP →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.