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
Example 1
Output: 1
Example 2
Output: 4
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 int100001010
Look at the picture below. Each number of Example 2 is one row, and each column is one bit position.
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
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 ^a ^ bint
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>
Sorting needs no set: after Arrays.sort(nums)int
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 ^ 44 ^ 1 ^ 2 ^ 1 ^ 24 ^ (1 ^ 1) ^ (2 ^ 2)4 ^ 0 ^ 0
Step by step, the running value for Example 2 goes 100101111110100
Negative numbers
Does a negative number need special handling? Java stores an int000…011111…101
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]
A shorter way with streams (optional)
Can the pass over the array be written in one line? Arrays.stream(nums)intreduce
int single = Arrays.stream(nums).reduce(0, (a, b) -> a ^ b);
Run on Example 2, it also returns 4. A plain for
Java Solution
The method singleNumber
- First, set the running value
to 0, so it holds no 1 bits yet.x - Loop over the array with an enhanced
loop, taking each number asfor . XOR it intonum withx , which flips the bits ofx ^= num wherex has a 1.num - After the loop, each pair has flipped its bits twice and left no trace, so
holds the bits of the single number. The method returnsx .x
The main[-3, 5, 5]intInteger.MIN_VALUE
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:
1
4
7
-3 = 11111111111111111111111111111101
-2147483648
The answers 1 and 4 match the two examples. The array [7]x
Look at the fourth line. Integer.toBinaryString101
The last line, -2147483648, is Integer.MIN_VALUE
What if xnums[0][2, 2, 1][4, 1, 2, 1, 2]
Complexity
The method makes a single pass over the array and keeps a single int
- Time: O(n), because each number in
is XOR-ed intonums exactly once, with no sorting and no lookups.x - Space: O(1), because
is all the method keeps, however many pairs the array holds, where ax of waiting numbers could hold half of them.HashSet
When two values appear once instead of one, XOR-ing everything leaves the two mixed together;