Distinguishing extra element from two arrays?

后端 未结 19 682
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 09:45

One of my friend was asked this question in an interview -

  • You have given two integer arrays each of size 10.
  • Both contains 9 equal elements (say 1 t
19条回答
  •  青春惊慌失措
    2020-12-28 10:35

    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:

    • As a (self-balanced) search tree. The tree has its elements sorted, thus looking up a particular element is efficient by using a binary search (or variant thereof). Lookup thus has a performance of O(log n). Creating the tree set from the input has performance O(n · log n). This is also the overall performance.
    • Hash tables can be implemented to have average-case look-up performance of O(1) (and with a few tricks, this can also be made the worst-case performance). Creating the hash table can be done in O(n). Therefore, hash tables can achieve an overall runtime of O(n).
    • Bloom filters offer a nice probabilistic solution – i.e. the solution may actually be wrong, but we can control how (un)likely this will be. It is particularly interesting because it’s very space-efficient.
    • … many other 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).

提交回复
热议问题