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. Return the answer in any order.
nums = [1,2,1,3,2,5][3,5]nums = [3,7,3,4][7,4]All pairs XOR to 0, leaving xor=a^b. Since a≠b, at least one bit differs. We pick the lowest such bit. It splits the array so one group has a (and a's pairs) and the other has b (and b's pairs). XOR within each group cancels the pairs, leaving the unique number.
A hash set works, but uses extra space. Plain XOR of everything gives 3 XOR 5, not the two numbers themselves.
XOR everything, and the pairs cancel, leaving x equal to a XOR b. Because a and b are different, x has at least one 1 bit, where a and b differ. Take the lowest set bit of x, using x AND minus x. Split the numbers into two groups by that bit, so a and b land in different groups. Pairs stay together, so XOR each group to get a and b.
One differing bit separates the two singles. x AND minus x isolates the lowest set bit.
Run the animation above on your own input, or watch the 1:37 video explanation of Single Number III with a dry run and Java code.