The Unpaired Sock

Easy · Bits & Math · about 10 min

A laundry machine tags every sock with a number, and both socks of a pair share the same number. After a wash, nums lists the tags of every sock found: each tag appears exactly twice, except one tag that appears exactly once (its partner is lost).

Return the tag that appears once. Tags can be negative or zero. Aim for one pass and constant extra memory.

  • 1 <= len(nums) <= 100001, len(nums) is odd, every tag fits in a 32-bit signed integer.

Examples:

unpaired_value([4, 1, 2, 1, 2]) → 4

unpaired_value([-3, 5, 5]) → -3

Hints

  • What is x XOR x? What is x XOR 0?
  • XOR is order independent, so XOR-ing the whole list cancels every pair, wherever the two socks are.

Learn the pattern first: the Bits & Math lesson.

More Bits & Math problems