One of my friend was asked this question in an interview -
The logic behind almost all of the previous answers is always the same: use set operations from mathematics to solve the problem.
A set in mathematics can contain each element only once. So the following list can’t be a set in the mathematical sense, since it contains one number (3) twice:
{ 1, 2, 3, 4, 3, 5 }
Since set operations, in particular checking whether an element already exists in a set, are common operations, most languages have data structures that implement these set operations efficiently. So we can simply fall back to this in our solution:
// Construct set from first list:
Set uniques = Set.from(list1);
// Iterate over second list, check each item’s existence in set.
for each (item in list2)
if (not uniques.Contains(item))
return item;
Different implementations of sets yield different performance, but this performance will always be superior to the naive solution (for large lists). In particular, two implementations exist:
In every case, the usage remains the same and the above pseudo-code gives a textbook solution to your problem. A Java implementation might look as follows:
// Construct set from first list:
Set uniques = new HashSet(list1);
// Iterate over second list, check each item’s existence in set.
for (int item : list2)
if (! uniques.Contains(item))
return item;
Notice how this looks almost exactly like the pseudo-code. Solutions in C#, C++ or other languages wouldn’t be much different.
EDIT Oops, I’ve just noticed that the requested return value is the pair of mismatching elements. However, this requirement doesn’t change the reasoning and almost doesn’t change the pseudo-code (do the same thing, with interchanged lists).