Single Number III (LeetCode 260): Solution and Explanation

Medium
Array
Bit Manipulation

Every value in nums appears twice except two values that appear once. Return those two values, in any order, using linear time and constant extra space.

Intuition

With one single value, XOR of the whole array is the answer, because each pair cancels (x ^ x = 0). With two singles a and b, the same XOR leaves a ^ b. That mixes them together, but it still tells us something useful.

a and b are different, so a ^ b has at least one bit set, and at every set bit a and b disagree: one has a 1 there, the other a 0. Pick any one of those bits. The lowest one is easy to isolate with xr & -xr.

Now split the whole array by that bit. Both copies of a duplicate have the same bits, so they always land on the same side and still cancel. a and b land on opposite sides. XOR each side on its own and each side collapses to exactly one of the singles.

Approach: XOR all, isolate a differing bit, XOR each group

  1. XOR every number into xr. Pairs cancel, so xr = a ^ b.
  2. Compute low = xr & -xr, the lowest set bit of xr. Exactly one of a, b has this bit.
  3. Walk the array again. XOR numbers with x & low != 0 into a, and the rest into b.
  4. Return [a, b].

Step-by-step example

nums = [1,2,1,3,2,5]
  1. Fold: 1 ^ 2 ^ 1 ^ 3 ^ 2 ^ 5. The 1s and 2s cancel, leaving xr = 3 ^ 5 = 011 ^ 101 = 110 = 6.
  2. low = 6 & -6 = 010 = 2. 3 (011) has bit 1 set and 5 (101) does not.
  3. Bit 1 set: 2, 3, 2. Their XOR is 3, so a = 3.
  4. Bit 1 clear: 1, 1, 5. Their XOR is 5, so b = 5.
  5. Return [3, 5].

Code: Python, Java, C++

1class Solution:
2    def singleNumber(self, nums: List[int]) -> List[int]:
3        xr = 0
4        for x in nums:
5            xr ^= x
6        low = xr & -xr
7        a = b = 0
8        for x in nums:
9            if x & low:
10                a ^= x
11            else:
12                b ^= x
13        return [a, b]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
XOR all, isolate a differing bit, XOR each group O(n)
Hash set or counter O(n)
Sort and scan O(n log n)
Time

O(n)

Two passes over the array with constant work per element.

Space

O(1)

Only xr, low, a and b are stored.

Other approaches

Hash set or counter (time O(n), space O(n))

Add a value to a set the first time you see it and remove it the second time; the two values left are the answer. Simple, but memory grows with the input.

Sort and scan (time O(n log n), space O(1))

Sort, then walk in steps: equal neighbors are a pair, a value whose neighbor differs is a single. No extra structure but O(n log n) time and it modifies the input.

Common mistakes

  • Computing -xr when xr is INT_MIN in C++. Negating INT_MIN is undefined behavior for signed ints, so do the trick on unsigned values or use xr & (~xr + 1).
  • Testing (x & low) == 1. The result is either 0 or low itself, which is 1 only when the bit is bit 0. Compare with 0 instead.
  • Splitting on a bit where xr is 0. Then a and b agree on that bit and land in the same group, which gives 0 and a ^ b.

Frequently asked questions

Why does xr & -xr keep only the lowest set bit?

In two's complement, -xr is ~xr + 1. Adding 1 to ~xr flips the trailing 1s back to 0s and turns the first 0 into a 1, which sits exactly at xr's lowest set bit. Every bit above it is the opposite of xr's, so AND keeps only that one bit.

Does it have to be the lowest set bit?

No. Any bit where xr has a 1 splits a and b. The lowest is just the cheapest one to isolate.

Can xr be 0?

No. xr equals a ^ b, and a and b are different values, so at least one bit differs.

Does the order of the answer matter?

No, either order is accepted. This solution returns the single with the split bit set first.