Opening the reading…
Opening the reading…
HASHING › IMPLEMENTARY PROBLEMS
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 →The result is not the XOR of all array elements. A number that appears once must contribute nothing, while a number that appears twice must contribute once. Since the values are limited to 1 through 50, you can record how many times each possible value occurs and later select only the entries with frequency two.
After counting, scan the possible values rather than the original array. For every value counted twice, XOR it into the answer exactly once. XOR combines selected values without caring about their order, and the initial answer of zero naturally remains correct when no value has frequency two.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n + 50), which is O(n) because n >= 1 | The first pass examines each of the n input elements once, and the second pass examines exactly 50 possible values. The two passes do not repeat input work, so their costs add rather than multiply. |
| Space | O(1) extra space | The frequency array always has 51 integer slots, independent of n. The returned integer is required output and is excluded from the working-space bound; there is no larger worst-case shape because the value range is fixed. |
#include <vector>
using namespace std;
class Solution {
public:
int duplicateNumbersXOR(vector<int>& nums) {
int freq[51] = {0};
for (int x : nums) {
freq[x]++;
}
int ans = 0;
for (int i = 1; i <= 50; i++) {
if (freq[i] == 2) {
ans ^= i;
}
}
return ans;
}
};The important placement is the second loop: it visits each possible value once, not each occurrence in nums. If value 1 appears twice, the loop still executes ans ^= 1 only once. That is what makes the contribution of a duplicate different from the contribution of a value that merely appears in the input.
Because the statement guarantees that a value appears at most twice, you can process nums once. The first occurrence marks the value as seen; the second occurrence XORs it into the answer. This works only because a third occurrence is impossible. It uses the same fixed amount of extra storage and removes the separate scan over values, but the two-pass version makes the exact-frequency condition more explicit.
#include <vector>
using namespace std;
class Solution {
public:
int duplicateNumbersXOR(vector<int>& nums) {
bool seen[51] = {false};
int ans = 0;
for (int x : nums) {
if (seen[x]) {
ans ^= x;
} else {
seen[x] = true;
}
}
return ans;
}
};