Single Number III

Find the two numbers that appear once in an array where every other number appears twice.

Given an array of integers nums in which exactly two numbers appear once and every other number appears exactly twice, return the two numbers that appear once, in any order. For an array of n numbers, the method must take time in proportion to n, written O(n), and use only a fixed amount of extra memory, O(1).

Example 1
Input: nums = [1, 2, 1, 3, 2, 5]
Output: [3, 5]
Example 2
Input: nums = [-1, 0]
Output: [-1, 0]
Solution

The Idea

Picture a drawer of gloves where every glove has its partner except two odd ones. Example 1 is such a drawer: in [1, 2, 1, 3, 2, 5] the two 1s make a pair, the two 2s make a pair, and 3 and 5 are left on their own. A table counting each number would find them, but the problem allows only a fixed amount of extra memory.

Working on the bits of the numbers gives a way to make pairs vanish. XOR, written ^ in Java, compares two numbers bit by bit and gives 1 where the bits differ and 0 where they agree. Bits are counted from the right, starting at bit 0. So 3 ^ 5 compares 011 with 101 and gives 110, which is 6.

Three facts about XOR matter here: a number XORed with itself gives 0, XOR with 0 changes nothing, and the order of the numbers does not change the result. XOR all six numbers of Example 1 together, and the 1s cancel, the 2s cancel, and 3 ^ 5 = 6 is left.

With one lonely number, as in Single Number, that would already be the answer. Here 6 is the two lonely numbers mixed together. How can 6 be pulled apart into 3 and 5?

Think about what a 1 bit in 6 means: at that position, 3 and 5 have different bits. Look at the picture below.

The numbers 1, 2, 1, 3, 2, 5 in binary, with columns for bit 2, bit 1 and bit 0. Their XOR is 110, which is 6. Splitting by bit 1 gives the group 2, 3, 2, whose XOR is 3, and the group 1, 1, 5, whose XOR is 5.

In the column labelled bit 1, 3 has a 1 and 5 has a 0. Now split all six numbers by that bit alone. The box labelled "bit 1 is 1" gets 2, 3 and 2, and the box labelled "bit 1 is 0" gets 1, 1 and 5. Both 2s land in the same box, because equal numbers have equal bits, and so do both 1s.

Inside each box the pairs cancel again, so the XOR of the group is 3 in one box and 5 in the other. Because 3 and 5 differ at bit 1, they always end up in different boxes. Each box then holds just one lonely number, and XOR finds it.

Solution Approach

Counting each number would be the simple way, but it does not fit the memory limit. The XOR idea needs three decisions instead: how to combine all the numbers, how to pick one bit where the two lonely numbers differ, and how to split the numbers by it.

Counting with a map

Why not just count? A HashMap from number to count, filled in one pass, shows which two numbers have a count of 1. That takes O(n) time, but the map holds about n/2 different numbers, so its memory grows with the array. The XOR approach keeps everything in a few int variables.

Combining all the numbers

What should the first pass compute? Start a variable xor at 0 and XOR each number into it. Order does not matter, so every number meets its partner sooner or later and the two cancel. The variable xor ends as the two lonely numbers XORed together.

That value is never 0. The two lonely numbers are different, so they differ in at least one bit, and that bit is 1 in xor.

Picking one differing bit

Which 1 bit of xor should do the splitting? Any of them works, and the lowest is the easiest to get, with xor & -xor. The & operator keeps a bit only where xor and -xor both have a 1.

Why does -xor help? Java keeps -xor in 32 bits using two's complement: it flips every bit of xor and then adds 1. With xor = 6, the last 8 of the 32 bits look like this:

ValueLast 8 bits (bit 7 to bit 0)
xor = 60000 0110
every bit flipped1111 1001
-xor, the flipped bits plus 11111 1010
xor & -xor0000 0010

Adding 1 to the flipped bits turns their trailing 1s back into 0s and stops at the first 0. That 0 sits exactly where xor has its lowest 1. Above that position, -xor is still the flipped xor, so the two share no 1 bits there, and below it both are 0.

So only the lowest 1 bit survives the &. For 6 the result is 0000 0010, which is 2, the bit 1 column in the picture.

Does this hold when the top bit, the sign bit, is the one that remains? If xor has only bit 31 set, it is Integer.MIN_VALUE, -2,147,483,648. Its negative, +2,147,483,648, does not fit in an int and wraps around to the same value, so xor & -xor still keeps that one bit.

Splitting the numbers

How is the split done without building two lists? A second pass tests each number with num & lowest, where lowest holds the chosen bit. A result other than 0 means the number has that bit set, so it belongs to the box for a 1 at that bit and is XORed into a variable a.

The other box needs no pass of its own. Since xor holds both lonely numbers XORed together, xor ^ a cancels a and leaves the other one.

Java Solution

The method singleNumber works in these steps:

  1. First, XOR every number into xor, which starts at 0. When this first loop ends, the pairs have cancelled and xor holds the two lonely numbers XORed together.
  2. Keep only the lowest 1 bit of xor in lowest, with xor & -xor.
  3. Loop over the numbers a second time. Each number with num & lowest other than 0 is XORed into a, which starts at 0. When this loop ends, a is the lonely number of that box.
  4. Return a and xor ^ a, the other lonely number.

The main method runs both examples, an array whose lonely numbers are the negative -6 and -9, and an array whose lonely numbers are Integer.MAX_VALUE and -1, which differ only in the sign bit.

Java
import java.util.Arrays;

public class SingleNumberIII {

    public static int[] singleNumber(int[] nums) {
        int xor = 0;
        for (int num : nums) {
            xor ^= num;                  // pairs cancel: the two lonely numbers are left
        }
        int lowest = xor & -xor;         // lowest 1 bit: the lonely numbers differ there
        int a = 0;
        for (int num : nums) {
            if ((num & lowest) != 0) {   // the group whose numbers have that bit set
                a ^= num;                // pairs in the group cancel, one answer is left
            }
        }
        return new int[] {a, xor ^ a};   // xor ^ a cancels a, leaving the other one
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(singleNumber(new int[] {1, 2, 1, 3, 2, 5})));
        System.out.println(Arrays.toString(singleNumber(new int[] {-1, 0})));
        System.out.println(Arrays.toString(singleNumber(new int[] {4, -6, 4, -9, 8, 8})));
        System.out.println(Arrays.toString(
                singleNumber(new int[] {Integer.MAX_VALUE, 9, -1, 9})));
    }
}

Running it prints:

Output
[3, 5]
[-1, 0]
[-9, -6]
[-1, 2147483647]

Example 1 prints [3, 5], with 3 first because it has bit 1 set, so the second loop collected it into a. In [-1, 0], xor is -1, which has all 32 bits set, so lowest keeps just bit 0. The number -1 has that bit and 0 does not, which gives [-1, 0].

The third line is [-9, -6]. In two's complement, -6 ends in the bits 1010 and -9 ends in 0111, so they differ at bit 0, and -9 is the one with bit 0 set. The last line, [-1, 2147483647], is the sign-bit case: xor is Integer.MIN_VALUE, lowest is that same top bit, and -1 is the number that has it.

Why split by one bit and not by xor itself? Testing num & xor instead puts a number into the box for a 1 if it shares any 1 bit with 6. In Example 1, 3 shares bit 1 and 5 shares bit 2, so that box gets 2, 3, 2 and 5. The method then returns [6, 0] instead of [3, 5].

Complexity

The method reads the array twice and keeps three int variables, whatever the length of the array.

  • Time: O(n), because each of the two loops visits the n numbers once and does one XOR or one bit test per number.
  • Space: O(1) besides the two-number result, because the method keeps only xor, lowest and a, where a counting map would grow with the number of different values.