~/problems / Bit manipulation

Single Number

easy ~10 min

A laundry machine hands back a pile of socks, each tagged with an integer ID. Every ID appears on exactly two socks, except for one ID that appears on a single sock. Find it.

Write find_unmatched(ids: list[int]) -> int that returns the ID that appears only once.

find_unmatched([8, 3, 5, 3, 5])   # 8
find_unmatched([7])               # 7
find_unmatched([-3, 5, 5])        # -3

Constraints:

  • 1 <= len(ids) <= 2 * 10^5 + 1, and len(ids) is odd.
  • IDs are in [-10^9, 10^9].
  • Exactly one ID appears once; every other ID appears exactly twice, in any order.

Aim for O(n) time and O(1) extra space: no dictionary, set or sorted copy.

Show hint

look for an operation on integers where combining a value with itself gives 0 and combining with 0 changes nothing. Apply it across the whole list and see what survives.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc