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
Example 1
Output: 3
Example 2
Output: 99
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
The answer comes from looking inside the numbers. A Java int1011
Now write the four numbers of Example 1 one under another and look at the picture below.
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 Java, "what is left over after groups of 3" is the remainder count % 3
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 numbitnum >>> bitnum& 111bit1& 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
Putting the answer together
Once a column's count is known, what do we do with it? If count % 31 << bitbit|=
Negative numbers
What about negative values? A Java int00
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 intonestwosonestwos
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 ^num~onestwos100000100100ones11singleNumber
Java Solution
The method singleNumber
- First, set
to 0. It has no bits turned on yet.result - Go through the 32 bit positions with an outer loop, using
from 0 to 31. For each position, start a counterbit at 0.count - Inside, a second loop goes through every
in the array and addsnum to(num >>> bit) & 1 , the number's bit at this position.count - After the inner loop, if
is not 0, turn on that bit incount % 3 withresult .result |= 1 << bit - After all 32 positions,
holds every bit of the single number, so the method returns it.result
The main
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:
3
99
-4
-1
7
11111111111111111111111111111100
The answers 3 and 99 match Examples 1 and 2. For 99, which is 1100011
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
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
- 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 and the loop variablecount , whatever the length of the array.bit
When every other value appears twice instead of three times, a single XOR over the array is enough: see