Opening the reading…
Opening the reading…
BIT MANIPULATION › BITWISE XOR OPERATOR
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →XOR removes pairs because x ^ x is 0, and XOR with 0 leaves a value unchanged. If you XOR the entire array, every repeated number disappears, leaving only uniqueA ^ uniqueB. That result is not either answer by itself, but it tells you that the two answers differ in at least one bit.
Choose any bit that is set in uniqueA ^ uniqueB. At that bit, one unique number has 1 and the other has 0. Partition every array value according to that bit. Each repeated value goes into the same group as its equal partner, while the two unique values go into different groups. XORing inside each group then cancels all pairs and leaves one unique value.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The algorithm scans the array once to combine all values and once to reduce the two groups. Each scan performs a fixed amount of bit work per element, so each element is processed a constant number of times and no nested traversal appears. |
| Space | O(1) extra | Only xorAll, the mask, and two integer accumulators are stored; their count does not grow with n. The returned two-element array is required output and is excluded from extra space. The bound stays constant even for the worst input shape because the algorithm never allocates a structure proportional to the array. |
#include <vector>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
unsigned int xorAll = 0;
for (int num : nums) {
xorAll ^= static_cast<unsigned int>(num);
}
unsigned int diffBit = xorAll & (0u - xorAll);
int a = 0;
int b = 0;
for (int num : nums) {
unsigned int value = static_cast<unsigned int>(num);
if (value & diffBit) {
a ^= num;
} else {
b ^= num;
}
}
return {a, b};
}
};The first pass does not try to identify either answer directly; it only discovers how the answers differ. The second pass turns that difference into a partition. The unsigned mask keeps the low-bit operation well-defined even when the differing bit is the sign bit, while the original values remain int values in the returned result.