Problems › JavaScript › patterns
The reading that only came once
Every sensor reports twice except one, whose second report went missing. Find the reading with no partner, without keeping the whole batch in memory.
- Every value appears exactly twice, except one that appears once.
- The batch is in no particular order.
- Return the value that appears once.
- An empty batch returns 0.
loneReading(batch: list<int>) → int
Where you start
function loneReading(batch) {
}
Worked examples
| Call | Result |
|---|---|
loneReading([4,1,2,1,2]) | 4 |
loneReading([2,2,1]) | 1 |
loneReading([7]) | 7 |
loneReading([]) | 0 |
Hint
A value exclusive-or’d with itself is zero, and order does not matter. Fold the whole batch together with xor and the pairs cancel out.
Reference solution in JavaScript
function loneReading(batch) {
let lone = 0;
for (const reading of batch) lone ^= reading;
return lone;
}