Single Number III (LeetCode 260): Solution and Explanation
Every value in nums appears twice except two values that appear once. Return those two values, in any order, using linear time and constant extra space.
Intuition
With one single value, XOR of the whole array is the answer, because each pair cancels (x ^ x = 0). With two singles a and b, the same XOR leaves a ^ b. That mixes them together, but it still tells us something useful.
a and b are different, so a ^ b has at least one bit set, and at every set bit a and b disagree: one has a 1 there, the other a 0. Pick any one of those bits. The lowest one is easy to isolate with xr & -xr.
Now split the whole array by that bit. Both copies of a duplicate have the same bits, so they always land on the same side and still cancel. a and b land on opposite sides. XOR each side on its own and each side collapses to exactly one of the singles.
Approach: XOR all, isolate a differing bit, XOR each group
- XOR every number into
xr. Pairs cancel, soxr = a ^ b. - Compute
low = xr & -xr, the lowest set bit ofxr. Exactly one of a, b has this bit. - Walk the array again. XOR numbers with
x & low != 0intoa, and the rest intob. - Return
[a, b].
Step-by-step example
nums = [1,2,1,3,2,5]
- Fold: 1 ^ 2 ^ 1 ^ 3 ^ 2 ^ 5. The 1s and 2s cancel, leaving xr = 3 ^ 5 = 011 ^ 101 = 110 = 6.
- low = 6 & -6 = 010 = 2. 3 (011) has bit 1 set and 5 (101) does not.
- Bit 1 set: 2, 3, 2. Their XOR is 3, so a = 3.
- Bit 1 clear: 1, 1, 5. Their XOR is 5, so b = 5.
- Return [3, 5].
Code: Python, Java, C++
1class Solution:
2 def singleNumber(self, nums: List[int]) -> List[int]:
3 xr = 0
4 for x in nums:
5 xr ^= x
6 low = xr & -xr
7 a = b = 0
8 for x in nums:
9 if x & low:
10 a ^= x
11 else:
12 b ^= x
13 return [a, b]1class Solution {
2 public int[] singleNumber(int[] nums) {
3 int xr = 0;
4 for (int x : nums) {
5 xr ^= x;
6 }
7 int low = xr & -xr;
8 int a = 0, b = 0;
9 for (int x : nums) {
10 if ((x & low) != 0) {
11 a ^= x;
12 } else {
13 b ^= x;
14 }
15 }
16 return new int[]{a, b};
17 }
18}1class Solution {
2public:
3 vector<int> singleNumber(vector<int>& nums) {
4 unsigned int xr = 0;
5 for (int x : nums) {
6 xr ^= x;
7 }
8 unsigned int low = xr & (~xr + 1);
9 int a = 0, b = 0;
10 for (int x : nums) {
11 if (x & low) {
12 a ^= x;
13 } else {
14 b ^= x;
15 }
16 }
17 return {a, b};
18 }
19};Time and space complexity
O(n)
Two passes over the array with constant work per element.
O(1)
Only xr, low, a and b are stored.
Other approaches
Hash set or counter (time O(n), space O(n))
Add a value to a set the first time you see it and remove it the second time; the two values left are the answer. Simple, but memory grows with the input.
Sort and scan (time O(n log n), space O(1))
Sort, then walk in steps: equal neighbors are a pair, a value whose neighbor differs is a single. No extra structure but O(n log n) time and it modifies the input.
Common mistakes
- Computing -xr when xr is INT_MIN in C++. Negating INT_MIN is undefined behavior for signed ints, so do the trick on unsigned values or use xr & (~xr + 1).
- Testing
(x & low) == 1. The result is either 0 or low itself, which is 1 only when the bit is bit 0. Compare with 0 instead. - Splitting on a bit where xr is 0. Then a and b agree on that bit and land in the same group, which gives 0 and a ^ b.
Frequently asked questions
Why does xr & -xr keep only the lowest set bit?
In two's complement, -xr is ~xr + 1. Adding 1 to ~xr flips the trailing 1s back to 0s and turns the first 0 into a 1, which sits exactly at xr's lowest set bit. Every bit above it is the opposite of xr's, so AND keeps only that one bit.
Does it have to be the lowest set bit?
No. Any bit where xr has a 1 splits a and b. The lowest is just the cheapest one to isolate.
Can xr be 0?
No. xr equals a ^ b, and a and b are different values, so at least one bit differs.
Does the order of the answer matter?
No, either order is accepted. This solution returns the single with the split bit set first.