#260

Single Number III

Medium XOR + lowest set bit

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Every number appears twice except two different numbers that appear once each. Return those two.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: two different loners, everything else in pairs.

Why this works: XOR of all = a ^ b, which has a 1 where a and b differ. Split all numbers by that bit; each group becomes the easy "single number" problem.

Example: [1, 2, 1, 3, 2, 5]

xor = 3 ^ 5 = 110lowest bit = 010group with bit: 2, 3, 2 → 3group without:  1, 1, 5 → 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using x & (x - 1) to pick the bit — that clears the lowest set bit instead of isolating it. Use x & -x.