Drill

ProblemsTypeScript › patterns

The reading that only came once

mediumpatternsBit manipulationArraysTypeScript

Every sensor reports twice except one, whose second report went missing. Find the reading with no partner, without keeping the whole batch in memory.

loneReading(batch: list<int>) → int

Solve it in the editor →

Where you start

function loneReading(batch: number[]): number {
  
}

Worked examples

CallResult
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 TypeScript
function loneReading(batch: number[]): number {
  let lone = 0;
  for (const reading of batch) lone ^= reading;
  return lone;
}

The same problem in another language

More patterns problems in TypeScript