Pergunta de entrevista da empresa Google

Given two linked lists, return the intersection of the two lists: i.e. return a list containing only the elements that occur in both of the input lists.

Respostas da entrevista

Sigiloso

13 de out. de 2009

Traverse the first list. Insert all the elements in the list into a hash table. Complexity: O(n) Traverse the second list. For each element in the list, look it up in the hash table. If it is in the hash table, then insert it into the destination list. Complexity: n * O(1) = O(n) Total complexity: O(n)

1

Sigiloso

27 de nov. de 2009

Here is where I am confused: A hashtable is supposed to have a O(1) lookup, is it not? The actual implementation of a hash table is platform specific. For e.g. C++ hashtables are Balanced binary search trees?

Sigiloso

8 de nov. de 2009

Hi Radu Litiu, Your solution is correct though the complexity analysis is incorrect. Insertion and lookup from the hashtable can take a worst case performance of O(n) or O(logn) if you use a priority queue as the backend storage. This means that while traversing the lists for n times, each time you can encounter a O(n) complexity thus resulting in a worst case performance of O(n^2), or at least O(nlogn).