Loading problem...
You are given an integer array nums that contains a special structure: exactly two elements appear only once, while every other element appears exactly twice. Your task is to identify and return these two unique singleton elements.
The result can be returned in any order — both orderings are considered correct.
The Challenge: Design an algorithm that achieves linear time complexity O(n) while using only constant extra space O(1). This constraint eliminates straightforward approaches like hash tables or sorting, requiring a clever application of bitwise operations.
Key Insight: Recall that XOR of a number with itself equals zero, and XOR of any number with zero yields the number itself. When you XOR all elements together, the duplicates cancel out, leaving you with the XOR of the two unique numbers. The challenge is then to separate these two numbers using only this combined XOR result.
nums = [1,2,1,3,2,5][3,5]In this array, numbers 1 and 2 each appear twice, canceling each other out. The only elements appearing exactly once are 3 and 5. Either [3,5] or [5,3] is a valid answer.
nums = [-1,0][-1,0]The array contains only two elements, and both appear exactly once. Since there are no duplicates to consider, the answer is simply these two elements: [-1,0] or [0,-1].
nums = [0,1][0,1]Similar to the previous example, both 0 and 1 appear exactly once. Either ordering [0,1] or [1,0] is accepted as correct.
Constraints