Single Number II

Find the one number that appears once when every other number appears three times, by counting bits.

Given an array of integers nums in which every value appears exactly three times except one value, which appears once, return that one value. The solution must take O(n) time for n numbers and use only a fixed amount of extra memory, however long the array is.

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

The Idea

Picture a drawer of socks that come in sets of three, all the same colour within a set. One sock has lost its two partners. In Example 1 the "socks" are 2, 2, 3 and 2: the three 2s form a full set, and 3 is the odd one out.

The plain way to find it is to count how often each value appears, for example in a HashMap from value to count, and return the value whose count is 1. That works, but the map grows with the number of different values, and the problem allows only a fixed amount of extra memory. So how can we find the single value without remembering every value we have seen?

The answer comes from looking inside the numbers. A Java int is stored as 32 binary digits, called bits, each 0 or 1. We number their positions from the right: position 0 is worth 1, position 1 is worth 2, position 2 is worth 4, and so on. So 2 is written 10 (a 1 at position 1), and 3 is 11 (1s at positions 1 and 0).

Now write the four numbers of Example 1 one under another and look at the picture below.

The numbers 2, 2, 3 and 2 in binary, with columns for position 1 and position 0. Position 1 has four 1s and position 0 has one 1. After taking away groups of 3, each column has 1 left over, so the answer is 11 in binary, which is 3.

Each column holds one bit position. The column labelled position 1 has four 1s: three from the 2s and one from the 3. The column labelled position 0 has a single 1, from the 3. Positions 2 to 31 are 0 in all four numbers.

Here is the key point. Each value that appears three times puts either three 1s or no 1s into a column. So if we take away full groups of 3 from a column's count, all of their 1s disappear. What is left over, 0 or 1, is the single number's bit at that position. In the row labelled "left over after groups of 3", both columns have 1 left, so the answer is 11 in binary, which is 3.

In Java, "what is left over after groups of 3" is the remainder count % 3. Counting one column at a time needs only one count, so the memory used stays the same for any array.

Solution Approach

Turning the column counts into code means settling three things: how to read one bit of a number, how to put the answer back together from its bits, and how negative numbers fit in. One more option keeps all 32 counts in two variables and reads the array only once.

Reading one bit

How do we tell whether a number has a 1 at a given position? Call the number num and the position bit. Java's shift operator num >>> bit slides all the binary digits of num to the right by that many places, so the bit we want lands at position 0. Then & 1 keeps only position 0 and clears everything else. For 3 (11) and bit = 1, the shift gives 1, and & 1 gives 1.

Adding that 0 or 1 for every number in the array gives the count of 1s in that column. Doing it for the 32 positions, one after another, covers every bit an int has.

Putting the answer together

Once a column's count is known, what do we do with it? If count % 3 is not 0, the single number has a 1 at that position, and we turn that bit on in the answer. The expression 1 << bit is a number with a single 1, at position bit. Combining it into the answer with |= (bitwise OR) sets that bit and leaves the others as they are.

Negative numbers

What about negative values? A Java int uses two's complement: the top bit, position 31, counts as -2,147,483,648 instead of +2,147,483,648, and the other 31 bits add their usual values. So -4 is thirty 1s followed by 00: a large negative top bit, with the lower bits adding back up to -4.

Position 31 is just another column, so nothing changes in the method. If the single number is negative, its position 31 has a 1 left over, the answer gets that bit, and the result comes out negative.

Optional: two variables as 32 counters

Can the 32 passes over the array become one? The counts only matter as 0, 1 or 2 after taking away groups of 3, and two bits can hold those three states. So two int variables, ones and twos, can hold all 32 counters at once, one bit position each. At each position, ones has a 1 when one 1 is left over, and twos has a 1 when two are left over.

Java
public static int singleNumberTwoMasks(int[] nums) {
    int ones = 0;
    int twos = 0;
    for (int num : nums) {
        ones = (ones ^ num) & ~twos;   // 1 where the count is now 1
        twos = (twos ^ num) & ~ones;   // 1 where the count is now 2
    }
    return ones;
}

Here ^ (XOR) flips the bits where num has a 1, and ~ flips every bit. On Example 1, written in binary, ones and twos go from 10 and 00 after the first 2, to 00 and 10 after the second 2. After the 3 they are 01 and 00: position 1 has reached three and starts again at 0. The last 2 leaves ones at 11, which is 3. The two-variable version reads the array once, but counting columns is easier to follow, so the method singleNumber in the full program below counts columns.

Java Solution

The method singleNumber works in these steps:

  1. First, set result to 0. It has no bits turned on yet.
  2. Go through the 32 bit positions with an outer loop, using bit from 0 to 31. For each position, start a counter count at 0.
  3. Inside, a second loop goes through every num in the array and adds (num >>> bit) & 1 to count, the number's bit at this position.
  4. After the inner loop, if count % 3 is not 0, turn on that bit in result with result |= 1 << bit.
  5. After all 32 positions, result holds every bit of the single number, so the method returns it.

The main method runs both examples, an array with negative numbers, a single number of -1, an array of one number, and prints -4 in binary.

Java
public class SingleNumberII {

    public static int singleNumber(int[] nums) {
        int result = 0;
        for (int bit = 0; bit < 32; bit++) {
            int count = 0;
            for (int num : nums) {
                count += (num >>> bit) & 1;        // 1 if num has a 1 at this position
            }
            if (count % 3 != 0) {
                result |= 1 << bit;                // the single number has a 1 here
            }
        }
        return result;
    }

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

Running it prints:

Output
3
99
-4
-1
7
11111111111111111111111111111100

The answers 3 and 99 match Examples 1 and 2. For 99, which is 1100011 in binary, the column at position 0 counts four 1s, three from the 1s and one from 99. Positions 1, 5 and 6 count one 1 each, all from 99.

The third line, -4, comes from an array where -2, 1 and 4 each appear three times. Its column at position 31 counts four 1s, three from the -2s and one from the -4, so one is left over and the result turns negative. The last line shows that top bit: -4 in binary is thirty 1s followed by 00, so its position 31 is a 1.

The fourth line, -1, has a 1 at all 32 positions, so every column keeps one left over. The fifth line, 7, shows that an array of a single number works too: every count is 0 or 1.

Complexity

The work is 32 passes over the array, one per bit position, and the memory is a few int variables.

  • Time: O(n), because each of the 32 bit positions reads all n numbers once, which is 32 · n bit reads, and 32 stays the same for every input.
  • Space: O(1), because the method keeps only result, count and the loop variable bit, whatever the length of the array.

When every other value appears twice instead of three times, a single XOR over the array is enough: see Single Number.