Single Number III
Medium
Topics
Given an array nums in which exactly two elements appear only once and all the others appear exactly twice, return the two single numbers sorted in ascending order. Use O(n) time and O(1) extra space.
Example 1
6, which is the XOR of the two unpaired values — so any bit set in it is a bit where they differ. Splitting the array by its lowest set bit puts one answer in each group and every pair wholly inside one group, reducing this to the single-number problem twice: 3 and 5.Input: nums = [1,2,1,3,2,5] Output: [3,5]
Example 2
Input: nums = [0,1] Output: [0,1]
Constraints
- 2 <= nums.length <= 3*10^4
- Exactly two elements appear once; the rest appear twice.
Editorial — intuition, approach, complexity and pitfalls
Intuition
XOR the whole array and the paired values cancel, leaving a ^ b for the two singletons. That is not yet an answer, but it is enough to separate them: since a != b, their XOR has at least one set bit, and at any such bit the two values differ.
Pick one — the lowest, via x & -x — and use it to split the array into two groups. Every paired value lands wholly in one group, so XOR-ing within each group cancels the pairs and leaves one singleton each. Two passes, no extra space.
Approach
- XOR everything to get
x = a ^ b. - Isolate the lowest set bit with
diff = x & -x. - Partition on that bit, XOR-ing each group separately.
- Return the two results in ascending order.
Dry Run
nums = [1,2,1,3,2,5]
xor of everything = 6 = 0b110 which is 3 ^ 5
lowest set bit = 2 = 0b10 partition on bit 1
bit set [2, 3, 2] xor = 3
bit clear [1, 1, 5] xor = 5
answer [3, 5]Complexity
- Time — O(n): two linear passes.
- Space — O(1): a handful of integers. The trailing two-element sort is a fixed comparison, not a sort over the input, so the constant-space claim survives it.
Common Pitfalls
- Using the highest set bit, or any arbitrary bit of
x. Any set bit works;x & -xis just the cheapest to compute. Picking a bit that is clear inxdoes not work, because then both singletons fall in the same group. - Writing
x & (x - 1)instead ofx & -x. That clears the lowest set bit rather than isolating it. - Forgetting to sort the pair when the problem asks for ascending order. Here it does.
- Using a hash set and removing seen values. O(n) time but O(n) space, and the problem names O(1).
- Trying to recover
aandbfroma ^ balone. One equation, two unknowns — the partition is what supplies the second equation. - In a fixed-width language, computing
-xon the minimum integer. It overflows to itself, which happens to give the right mask, but the reasoning deserves a sentence rather than luck.
Full Solution — all languages
class Solution:
def singleNumber(self, nums):
x = 0
for v in nums:
x ^= v
diff = x & (-x)
a = b = 0
for v in nums:
if v & diff:
a ^= v
else:
b ^= v
return sorted([a, b])import java.util.*;
class Solution {
public int[] singleNumber(int[] nums) {
int xorAll = 0;
for (int v : nums) xorAll ^= v;
int diff = xorAll & (-xorAll);
int a = 0, b = 0;
for (int v : nums) {
if ((v & diff) != 0) a ^= v;
else b ^= v;
}
return new int[]{Math.min(a, b), Math.max(a, b)};
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> singleNumber(vector<int>& nums) {
int xorAll = 0;
for (int v : nums) xorAll ^= v;
int diff = xorAll & (-xorAll);
int a = 0, b = 0;
for (int v : nums) {
if (v & diff) a ^= v;
else b ^= v;
}
return {
min(a, b), max(a, b)
};
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var singleNumber = function(nums) {
let xorAll = 0;
for (const v of nums) xorAll ^= v;
const diff = xorAll & (-xorAll);
let a = 0, b = 0;
for (const v of nums) {
if (v & diff) a ^= v;
else b ^= v;
}
return [Math.min(a, b), Math.max(a, b)];
};