Single Number

Find the one value in an array that has no partner, by letting XOR cancel every pair.

Given a non-empty array of integers nums in which every value appears exactly twice except one, return the value that appears only once. The time may grow only in step with the length of the array, written O(n), and the extra memory must stay fixed however long the array is, written O(1).

Example 1
Input: nums = [2, 2, 1]
Output: 1
Example 2
Input: nums = [4, 1, 2, 1, 2]
Output: 4
Solution

The Idea

Picture a basket of clean socks in which every sock has a partner except one. To find the odd one out, you could take socks out one by one and lay each aside until its partner turns up. The sock still lying alone at the end is the answer.

Example 2 works the same way. Lay aside 4, then 1, then 2. The second 1 meets the first and both go away, and the second 2 does the same. Only 4 is left. In code, the socks lying aside would be a set of numbers that can grow to about half the array. The problem allows only a fixed amount of memory, so how can we keep track of what is waiting without that pile?

The answer lies in how the numbers are stored. Each of these numbers is a Java int, a row of 32 bits that are each 0 or 1. The rightmost bit is position 0 and is worth 1, position 1 is worth 2, and position 2 is worth 4. So 4 is 100, 1 is 001 and 2 is 010, written with only positions 2, 1 and 0, since the higher positions all hold 0 here.

Look at the picture below. Each number of Example 2 is one row, and each column is one bit position.

The numbers 4, 1, 2, 1, 2 written in binary with bit positions 2, 1 and 0. Position 2 holds one 1 bit (odd), positions 1 and 0 hold two 1 bits each (even). The XOR of all five is 100, which is 4.

Read down a column and count its 1 bits. The 1 appears twice, so the column under position 0 holds two 1 bits. The 2 appears twice too, which gives position 1 two 1 bits. Only the 4 has a 1 bit at position 2, so that column holds one, an odd count. In the row labelled "XOR of all five", a position gets 1 where its column count is odd and 0 where it is even: 100, which is 4.

Why does this hold for any input? A value that appears twice adds its 1 bits to the same columns twice, so it never changes whether a column count is odd or even. The single number alone decides that, so the odd columns spell out exactly its bits.

Keeping only "odd or even" for each column is what the XOR operator does, short for "exclusive or" and written ^ in Java. At each bit position, a ^ b gives 1 when exactly one of the two bits is 1, and 0 when they are equal. XOR-ing a running value with a number therefore flips the bits where that number has a 1. A pair flips the same bits twice, which puts them back, so one int replaces the whole pile of waiting numbers.

Solution Approach

Turning that idea into code means three things: seeing why the simpler ways miss the limits, choosing where the running value starts, and checking negative numbers. There is also an optional shorter version with streams.

The simpler ways and their cost

Why not keep the pile from the basket of socks? A HashSet<Integer> that adds a number the first time it shows up and removes it the second time ends up holding only the single number. It takes O(n) time, but the set can hold about n/2 numbers at once, so its memory grows with the array.

Sorting needs no set: after Arrays.sort(nums) each pair sits side by side, and one pass finds the value without a neighbour equal to it. But sorting takes O(n log n) time, more than the O(n) the problem allows. XOR keeps one int and reads each number once, so it meets both limits.

Where the running value starts

What should the running value hold before the first number arrives? It starts at 0, because 0 has no 1 bits and so flips nothing: 0 ^ 4 is 4. The order of the numbers does not matter either. XOR can be applied in any order and grouped in any way. So 4 ^ 1 ^ 2 ^ 1 ^ 2 equals 4 ^ (1 ^ 1) ^ (2 ^ 2), which is 4 ^ 0 ^ 0, or 4.

Step by step, the running value for Example 2 goes 100 (4), 101 (5), 111 (7), 110 (6) and back to 100 (4). The two 1s cancel even though the 2 sits between them.

Negative numbers

Does a negative number need special handling? Java stores an int in 32 bits using two's complement: to get -3, take the bits of 3, flip every one of them, and add 1. That turns 000…011 into 111…101, with 1 bits from position 31 down to position 2.

XOR never asks what the bits mean. It flips them position by position, all 32 of them, and a pair of equal negative numbers flips the same positions twice. So [-3, 5, 5] gives -3 with no extra code.

A shorter way with streams (optional)

Can the pass over the array be written in one line? Arrays.stream(nums) turns the array into a stream of int values, and reduce folds them into one value, starting from 0 and combining with XOR:

Java
int single = Arrays.stream(nums).reduce(0, (a, b) -> a ^ b);

Run on Example 2, it also returns 4. A plain for loop does the same work, one visible step per number.

Java Solution

The method singleNumber works in these steps:

  1. First, set the running value x to 0, so it holds no 1 bits yet.
  2. Loop over the array with an enhanced for loop, taking each number as num. XOR it into x with x ^= num, which flips the bits of x where num has a 1.
  3. After the loop, each pair has flipped its bits twice and left no trace, so x holds the bits of the single number. The method returns x.

The main method runs both examples, an array of one number, and [-3, 5, 5], printed with all 32 bits of its answer. Last comes an array where 0 and -1 form pairs and the smallest int, Integer.MIN_VALUE, appears once.

Java
public class SingleNumber {

    public static int singleNumber(int[] nums) {
        int x = 0;
        for (int num : nums) {
            x ^= num;       // flips the bits where num has a 1; a pair flips them back
        }
        return x;
    }

    public static void main(String[] args) {
        System.out.println(singleNumber(new int[] {2, 2, 1}));
        System.out.println(singleNumber(new int[] {4, 1, 2, 1, 2}));
        System.out.println(singleNumber(new int[] {7}));
        int neg = singleNumber(new int[] {-3, 5, 5});
        System.out.println(neg + " = " + Integer.toBinaryString(neg));
        System.out.println(singleNumber(new int[] {0, -1, Integer.MIN_VALUE, -1, 0}));
    }
}

Running it prints:

Output
1
4
7
-3 = 11111111111111111111111111111101
-2147483648

The answers 1 and 4 match the two examples. The array [7] prints 7: there is nothing to cancel, so x goes from 0 to 7 in one step.

Look at the fourth line. Integer.toBinaryString shows the 32 bits of -3: thirty 1 bits, then 0 at position 1 and 1 at position 0, the two's complement pattern of -3. Both 5s, 101, flipped positions 2 and 0 twice and left those bits as they were.

The last line, -2147483648, is Integer.MIN_VALUE, whose only 1 bit is at position 31. The two -1s have all 32 bits set and flip every position twice, and the two 0s flip nothing, so that single bit is what remains.

What if x started at nums[0] instead of 0, with the loop still going over the whole array? The first number then gets XOR-ed in twice and cancels itself. Run that way, [2, 2, 1] returns 3 instead of 1, and [4, 1, 2, 1, 2] returns 0 instead of 4.

Complexity

The method makes a single pass over the array and keeps a single int.

  • Time: O(n), because each number in nums is XOR-ed into x exactly once, with no sorting and no lookups.
  • Space: O(1), because x is all the method keeps, however many pairs the array holds, where a HashSet of waiting numbers could hold half of them.

When two values appear once instead of one, XOR-ing everything leaves the two mixed together; Single Number III shows how to pull them apart.