The one value without a partner

Bits and maths Junior Python 3.13+ Kotlin 2.4+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
from functools import reduce
from operator import xor
print(reduce(xor, [4, 1, 2, 1, 2]), 5 ^ 5, 7 ^ 0)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 4 0 7

Right: the pairs of 1 and 2 cancel, x ^ x is 0, and x ^ 0 is x.

Because order does not matter for XOR, the pairs can sit anywhere in the list and still cancel.

Why not the others?
  • B 10 0 7. XOR does not add; it cancels equal bits.
  • C 4 5 7. A value XOR itself is 0.

30-second answer

XOR all the values. XOR is associative and commutative, x ^ x = 0 and x ^ 0 = x, so every pair cancels and only the unpaired value remains. O(n) time, O(1) memory.

Practise saying it · 30 s. No recording, just a timer

Explain finding the unpaired value with XOR.

Say your answer out loud, then check which of these points you covered:

  • x ^ x = 0
  • x ^ 0 = x
  • O(1) memory

Deep dive

XOR as 'cancel pairs' is the bit-trick template.

A set or Counter works in O(n) memory and is a fine first answer.

With two unpaired values, split by any bit where their XOR is 1 and XOR each group.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def unpaired(vals: list[int]) -> int:
    acc = 0
    for v in vals:
        acc ^= v  # equal pairs cancel to 0
    return acc

Kotlin Ran on Kotlin 2.4.21 · JDK 21.0.12.1
Kotlin 2.4
fun unpaired(vals: List<Int>): Int {
    var acc = 0
    for (v in vals) acc = acc xor v // equal pairs cancel to 0
    return acc
}

Common mistakes

  • Using a sum, which does not cancel pairs.
  • Sorting first, which costs O(n log n) for no gain.

Senior take & follow-ups

Name the three XOR rules out loud; the answer follows from them.

Follow-up questions

Think of your answer first, then open the hint.

  1. What if every other value appears three times?

    Show hint

    Count each bit position modulo 3 across all values.

  2. How do you find two unpaired values?

    Show hint

    XOR all to get a ^ b, take its lowest 1 bit, and XOR the two groups split by that bit.

What each operation costs: Hash Functions

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.