One of my friend was asked this question in an interview -
Here is a mathematical approach, inspired by Kevin's answer and its comments.
Let's call the arrays A
and B
and let their unique elements be a
and b
, respectively. First, take the sums of both arrays and subtract one from the other; since everything else cancels, sum(A) - sum(B) = a - b = s
. Then, multiply the elements of both arrays and divide one by the other. Again, things cancel, so mult(A) / mult(B) = a / b = r
. Now, from these, we get a = rb
, so rb - b = s
or b = s / (r - 1)
and then a = rs / (r - 1)
.
I'm calling this mathematical because multiplying things out might not be a reasonable thing to do in a real program. The key is to have two different operations that both individually allow the canceling behavior and so that one distributes over the other. This latter property is used when going from rb - b = s
to b = s / (r - 1)
, and that won't work, say, with addition and XOR, which was my first attempt.