Reading preferences
Concept

Bitwise XOR for Paired Values

Cancel pairs to find one unpaired integer under a precise contract.

python, bitwise, xor, integers

Cancel equal pairs

XOR compares bits: equal bits give 0 and different bits give 1. XOR is associative and commutative; a value XOR itself is zero and XOR with zero leaves the value unchanged.

Python illustration

def single_value(values):
    result = 0
    for value in values:
        result ^= value
    return result

print(single_value([5, 2, 5, 7, 2]))

Prepared output: 7.

See the reasoning

Follow the example one step at a time

Cancel pairs without depending on their order. This is a prepared teaching demonstration, not live code execution.

Accumulate

0 XOR 5 XOR 2 XOR 5 XOR 7 XOR 2

The accumulator combines all values.

State the promise

If exactly one integer occurs once and every other integer occurs twice, reordering the XOR groups each pair into zero and leaves the single value. The function does not verify the promise: an empty input or different frequencies produce an XOR but not necessarily a meaningful answer. With fixed-width arithmetic it uses O(n) time and O(1) extra words. Python integers have arbitrary precision, so bit width affects time and memory. Negative integers are supported by Python's bitwise semantics; this is not a general replacement for counting.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What is x XOR x?
2. What is x XOR zero?
3. When does this method identify the intended single value?
4. What extra storage does the accumulator use?

References and further reading