Single Number III

medium

Given an integer array nums, exactly two elements appear only once and every other element appears exactly twice. Find and return the two elements that appear only once. You may return the answer in any order.

Your solution must run in linear time and use only constant extra space.

Hints

XOR the whole array. Since the pairs cancel, what single value are you left with?
That value is a ^ b. Any bit set in it is a position where the two loners differ.
Split the numbers by one such bit and XOR each group — each loner ends up alone.

Common doubts

Every paired value cancels itself under XOR (x ^ x = 0), so only the two unpaired values survive, combined as a ^ b.
Any set bit of a ^ b works — each marks a position where the two loners disagree. The lowest one, x & (-x), is the simplest to grab.
Both copies of a paired value share every bit, so they always fall into the same bucket and cancel there — leaving each bucket with exactly one loner.

Interview follow-ups

A single differing bit no longer cleanly separates them. You need a more elaborate scheme (e.g. combining the count-bits-mod-k idea with grouping), which is why the two-loner case is the clean one.
All three are the same reflex — cancel duplicates with bit arithmetic. One loner: XOR. One loner among triples: count bits mod 3. Two loners: XOR then split on a differing bit.

Fun facts

  • x & (-x) isolating the lowest set bit is the same operation a Fenwick (binary indexed) tree uses to walk its ranges.
  • Splitting a set by one bit and recombining is the seed of radix-based ideas like radix sort and binary tries.

Asked at

AmazonGoogleMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [1, 2, 1, 3, 2, 5]
Output: [3, 5]
1 and 2 each appear twice and cancel; 3 and 5 are the two singles. [5, 3] is also accepted.
Example 2
Input: nums = [-1, 0]
Output: [-1, 0]
Both values appear once; there are no pairs to cancel.
Example 3
Input: nums = [0, 1]
Output: [0, 1]
Two elements, each appearing once.
Constraints

- 2 <= nums.length <= 3 * 10^4 - -2^31 <= nums[i] <= 2^31 - 1 - Exactly two elements appear only once and all the other elements appear exactly twice.

Solve this problem →