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 can return the answer in any order.

Input: nums = [1, 2, 1, 3, 2, 5]
Output: [3, 5]
Explanation: 3 and 5 each appear once; 1 and 2 appear twice.
Input: nums = [-1, 0]
Output: [-1, 0]
Explanation: Both -1 and 0 appear once.

XOR all numbers to get xor = a ^ b where a and b are the two unique numbers. Since a != b, xor != 0. Find any set bit in xor (e.g., the lowest set bit using xor & (-xor)). Use this bit to partition numbers into two groups — a and b will fall in different groups. XOR each group separately to recover a and b.

class Solution { public int[] singleNumber(int[] nums) { int xor = 0; for (int num : nums) xor ^= num; // Find lowest set bit to distinguish a and b int diff = xor & (-xor); int a = 0; for (int num : nums) { if ((num & diff) != 0) { a ^= num; } } return new int[]{a, xor ^ a}; } }
Complexity Analysis:

Time complexity: O(n) — two passes through the array.
Space complexity: O(1) — constant extra space.