progress

~/problems / Bit manipulation

Single Number

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A laundry machine hands back socks tagged with integer IDs. Every ID appears on exactly two socks, except one that appears once. Find it.

Write find_unmatched(ids: list[int]) -> int.

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

Up to 2 * 10^5 + 1 IDs, each in [-10^9, 10^9], in any order.

⭐ Bonus: a speed test with 200,000 IDs earns a star in O(n) time. For the real trick, use O(1) extra space too: no dictionary, set or sorted copy.

Show hint

find an operation where combining a value with itself gives 0 and combining with 0 changes nothing. Apply it across the list.

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