Problem Description
Given an integer array where exactly two elements appear only once and all the other elements appear exactly twice, find the two elements that appear only once. The answer can be returned in any order.
Key Insights
- XOR of two identical numbers is 0.
- XOR of all numbers results in the XOR of the two unique numbers.
- A set bit in the XOR results (xorTotal) indicates a bit position where the two unique numbers differ.
- Partitioning the array based on this set bit allows isolation of each unique number.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
Use XOR to combine all numbers, which cancels out the pairs and leaves the XOR of the two unique numbers. Identify any set bit in this XOR to differentiate between the two unique numbers. Partition the numbers based on whether they have that bit set and XOR each group separately. The result are the two unique numbers. This approach leverages bit manipulation with constant extra space and a single pass (or two passes) over the input.