AlgoInsight

DSA problem

Single Number III

MediumBit ManipulationPattern: XORtop75AmazonGoogleFacebook

Given an integer array nums in which exactly two elements appear only once and all the other elements appear exactly twice, find the two elements that appear only once. You may return the answer in any order.

You must write an algorithm that runs in linear time and uses only constant extra space.

XOR-ing the entire array cancels every paired element and leaves xorAll = a ^ b, where a and b are the two unique numbers. Since a and b are distinct, xorAll has at least one set bit; that bit position is where a and b differ.

Pick any one such set bit (conveniently the lowest, via xorAll & -xorAll). This bit partitions the array into two groups: numbers with the bit set and numbers without it. Each unique number falls into a different group, and every duplicate pair lands together in the same group. XOR-ing each group separately recovers a and b.

Examples

Example 1
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: The numbers 3 and 5 each appear once; all others appear twice. [5,3] is also accepted since order does not matter.
Example 2
Input: nums = [-1,0]
Output: [-1,0]
Explanation: Both -1 and 0 appear exactly once, so they are the two unique elements.
Example 3
Input: nums = [0,1]
Output: [1,0]
Explanation: Both values appear exactly once and may be returned in any order.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulationarrayxor

Browse all DSA problems