Drill

ProblemsPython › patterns

The reading that only came once

mediumpatternsBit manipulationArraysPython

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

lone_reading(batch: list<int>) → int

Solve it in the editor →

Where you start

def lone_reading(batch: list[int]) -> int:
    

Worked examples

CallResult
lone_reading([4, 1, 2, 1, 2])4
lone_reading([2, 2, 1])1
lone_reading([7])7
lone_reading([])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 Python
def lone_reading(batch: list[int]) -> int:
    lone = 0
    for reading in batch:
        lone ^= reading
    return lone

The same problem in another language

More patterns problems in Python